"""
v0 script written by Myriam Benisty and Stefano Facchini (Feb 2st 2022)
v1 version adapted by Stefano Facchini and Myriam Benisty (Mar 2nd 2022)
v2 version adapted to include ACA data by Jane Huang and compacted code by Gianni Cataldi (May 19th 2022)
v3 (current version) includes EB alignment by Ryan Loomis and Richard Teague (Aug 2022)


This script is written for CASA 6.2.1.7. 
It can easily be adapted to other versions of CASA, e.g. by modifying the fixvis task to phaseshift task.

The numba package is used for the alignment script, but it is not necessary (it helps with the speed-up)

The scripts are written to be compatible mpicasa.
However, after testingthe exoALMA collaboration decided not to use mpicasa in any of the calibration scripts,
since they realized that differences in the results between casa and mpicasa could arise.

Person in charge for this source:
M. Benisty

"""

import os
import numpy as np

#path to your local copy of the gihub repository
#(make sure to do a 'git pull' to have the most up-to-date version)
github_path = '/users/mbenisty/calibration_scripts'
import sys
sys.path.append(github_path)
import alignment
execfile(os.path.join(github_path,'reduction_utils_exoalma.py'))
#increase the number of figures that can be open before issuing a warning
matplotlib.rcParams.update({'figure.max_open_warning':80})

prefix = 'J1615'

data_folderpath = '/lustre/cv/projects/exoALMA/ALMA_PL_calibrated_data/J1615-3255'
TM_names = {'LB':'TM1','SB':'TM2', 'ACA':'ACA'}
PL_calibrated_vis = {key:os.path.join(data_folderpath,f'{TM_name}/calibrated_final.ms')
                     for key,TM_name in TM_names.items()}

for baseline_key,TM_name in TM_names.items():
    listobs(
        vis=PL_calibrated_vis[baseline_key],
        listfile=f'{prefix}_{TM_name}_calibrated_final.ms.txt',
        overwrite=True,
    )

listobs(
    vis=data_folderpath+'/TM1/EB0_fixed.ms',
    listfile=f'{prefix}_TM1_EB0_fixed.ms.txt',
    overwrite=True,
)
# EB0 has 80 spws (from 0 to 79)

listobs(
    vis=data_folderpath+'/TM1/EB1_fixed.ms',
    listfile=f'{prefix}_TM1_EB1_fixed.ms.txt',
    overwrite=True,
)
# EB1 has 72 spws (from 0 to 71, since it has 18 scans)

# System properties.

incl = 47.1   # Bohn et al. 2022
PA   = 145    # Bohn et al. 2022
v_sys = 4.7   # km/s; use the one from listobs

# Whether to run tclean in parallel or not.

use_parallel = False

fields = {'ACA':'RXJ1615.3-3255','SB':'RXJ1615.3-3255','LB':'RXJ1615.3-3255'}

number_of_EBs = {'ACA':3,'SB':2,'LB':4}

for baseline_key,vis in PL_calibrated_vis.items():
    split_all_obs(msfile=vis,nametemplate=f'{prefix}_{baseline_key}_EB')

for baseline_key,n_EB in number_of_EBs.items():
    for i in range(n_EB):
        vis = f'{prefix}_{baseline_key}_EB{i}.ms'
        listobs(
            vis=vis,
            listfile=f'{vis}.txt',
            overwrite=True,
        )

"""
Check that spws and field numbering is what you expect them to be now from the listobs files
In particular, make sure that there are 4 spws and that there is a single field with
field ID = 0
"""

"""
In this case, we remove EB0 and EB1 of TM1, and we copy EB0_fixed and EB1_fixed here
"""
os.system('rm -rf J1615_LB_EB0.ms*')
os.system('rm -rf J1615_LB_EB1.ms*')

os.system('cp -r ../../TM1/EB0_fixed.ms J1615_LB_EB0.ms')
os.system('cp -r ../../TM1/EB1_fixed.ms J1615_LB_EB1.ms')

# Line rest frequencies from splatalogue (https://splatalogue.online)
rest_freq_12CO = 345.79598990e9 #J=3-2
rest_freq_13CO = 330.58796530e9 #J=3-2 (ignoring splitting)
rest_freq_CS   = 342.88285030e9 #J=7-6

data_params_LB = {'LB0': {'vis' : f'{prefix}_LB_EB0.ms',
                          'name' : 'LB_EB0',
                          'field' : fields['LB'],
                          'line_spws': np.array([0,2,3,
                                                 4,6,7,
                                                 8,10,11,
                                                 12,14,15,
                                                 16,18,19,
                                                 20,22,23,
                                                 24,26,27,
                                                 28,30,31,
                                                 32,34,35,
                                                 36,38,39,
                                                 40,42,43,
                                                 44,46,47,
                                                 48,50,51,
                                                 52,54,55,
                                                 56,58,59,
                                                 60,62,63,
                                                 64,66,67,
                                                 68,70,71,
                                                 72,74,75,
                                                 76,78,79]), # list of spws containing lines
                          'line_freqs': np.array([rest_freq_13CO,rest_freq_CS,rest_freq_12CO]*20), #frequencies (Hz) corresponding to line_spws
                          'cont_spws': None,
                          'width_array': None,
                          },                          
                  'LB1': {'vis' : f'{prefix}_LB_EB1.ms',
                          'name' : 'LB_EB1',
                          'field' : fields['LB'],
                          'line_spws': np.array([0,2,3,
                                                 4,6,7,
                                                 8,10,11,
                                                 12,14,15,
                                                 16,18,19,
                                                 20,22,23,
                                                 24,26,27,
                                                 28,30,31,
                                                 32,34,35,
                                                 36,38,39,
                                                 40,42,43,
                                                 44,46,47,
                                                 48,50,51,
                                                 52,54,55,
                                                 56,58,59,
                                                 60,62,63,
                                                 64,66,67,
                                                 68,70,71]), # list of spws containing lines
                          'line_freqs': np.array([rest_freq_13CO,rest_freq_CS,rest_freq_12CO]*18), #frequencies (Hz) corresponding to line_spws
                          'cont_spws': None,
                          'width_array': None,
                          },
                  'LB2': {'vis' : f'{prefix}_LB_EB2.ms',
                          'name' : 'LB_EB2',
                          'field' : fields['LB'],
                          'line_spws': np.array([0,2,3]), # list of spws containing lines
                          'line_freqs': np.array([rest_freq_13CO,rest_freq_CS,rest_freq_12CO]), #frequencies (Hz) corresponding to line_spws
                          'cont_spws': None,
                          'width_array': None,
                          },
                  'LB3': {'vis' : f'{prefix}_LB_EB3.ms',
                          'name' : 'LB_EB3',
                          'field' : fields['LB'],
                          'line_spws': np.array([0,2,3]), # list of spws containing lines
                          'line_freqs': np.array([rest_freq_13CO,rest_freq_CS,rest_freq_12CO]), #frequencies (Hz) corresponding to line_spws
                          'cont_spws': None,
                          'width_array': None,
                          },        
                }

data_params_SB = {f'SB{i}': {'vis' : f'{prefix}_SB_EB{i}.ms',
                          'name' : f'SB_EB{i}',
                          'field' : fields['SB'],
                          'line_spws': np.array([0,2,3]), # list of spws containing lines
                          'line_freqs': np.array([rest_freq_13CO,rest_freq_CS,rest_freq_12CO]), #frequencies (Hz) corresponding to line_spws
                          'cont_spws': None,
                          'width_array': None,
                          }
               for i in range(number_of_EBs['SB'])}

data_params_ACA = {f'ACA{i}': {'vis' : f'{prefix}_ACA_EB{i}.ms',
                           'name' : f'ACA_EB{i}',
                           'field' : fields['ACA'],
                           'line_spws': np.array([0,2,3]), # list of spws containing lines
                           'line_freqs': np.array([rest_freq_13CO,rest_freq_CS,rest_freq_12CO]), #frequencies (Hz) corresponding to line_spws
                           'cont_spws': None,
                           'width_array': None,
                           }
               for i in range(number_of_EBs['ACA'])}

data_params = data_params_LB.copy()
data_params.update(data_params_SB)
data_params.update(data_params_ACA)


figures_foldername = 'figures'
os.mkdir(figures_foldername)

def get_figures_folderpath(foldername):
    return os.path.join(figures_foldername,foldername)

def make_figures_folder(folderpath):
    if os.path.isdir(folderpath):
        print(f'going to deleted folder {folderpath} and its content')
        valid_answer = 'yes'
        answer = input(f'to confirm, type \'{valid_answer}\': ')
        if answer == valid_answer:
            shutil.rmtree(folderpath)
        else:
            print('aborting')
            return
    os.mkdir(folderpath)
    return folderpath

preselfcal_amp_figures_folder = get_figures_folderpath('1_preselfcal_amp_figures')
make_figures_folder(preselfcal_amp_figures_folder)

#adjust these plot ranges according to your data
plotranges = {'ACA':[0,500,0,0.5], #xmin,xmax,ymin,ymax
              'SB':[0,1000,0,0.5],
              'LB':[0,1500,0,0.5]}


for params in data_params.values():
    plotms(vis=params['vis'],
            xaxis='channel',
            yaxis='amplitude',
            field=params['field'],
            ydatacolumn='data',
            avgtime='1e8',
            avgscan=True,
            avgbaseline=True,
            #There is a bug in plotms that plots the data wrongly if there is unequal flagging
            #between the polarisations
            #the bug occurs if we plot amp and we average over baselines
            #thus we color by polarization such that
            #we easily identify this issue
            #if you find issues, then try plotting XX and YY polarisation separately
            #to verify that it is only a plotms bug and not a problem with the data
            coloraxis='corr',
            iteraxis='spw',
            showgui = False,
            exprange='all',
            plotfile=os.path.join(preselfcal_amp_figures_folder,
                                  prefix+'_'+params['name']+'_chan-v-amp_preselfcal.png'))
    baseline_key = params['name'].split('_')[0]
    plotms(vis=params['vis'],
            xaxis='UVdist',
            yaxis='amplitude',
            spw='1',
            field=params['field'],
            ydatacolumn='data',
            avgtime='1e8',
            avgscan=True,
            avgchannel='3840',
            showgui = False,
            plotrange=plotranges[baseline_key],
            plotfile=os.path.join(preselfcal_amp_figures_folder,
                                  prefix+'_'+params['name']+'_uvdist-v-amp_cont_spw_preselfcal.png'))


for params in data_params.values():
    flagchannels_string = get_flagchannels(ms_dict=params,output_prefix=prefix,
                                           velocity_range = np.array([-15., 15.])+v_sys)
    avg_cont(ms_dict=params, output_prefix=prefix, flagchannels = flagchannels_string,
             contspws = params['cont_spws'], width_array=params['width_array'])



"""
Double-check that the channels idenfified are at the center of the spws,
due to a potential issue with the data_desc_id key in the ms table of some programs
"""
# Flagchannels input string for LB_EB0: '0:832~3000, 2:799~3047, 3:784~3051, 4:832~3000, 6:799~3047, 7:784~3051, 8:832~3000, 10:799~3047, 11:784~3051, 12:832~3000, 14:798~3047, 15:783~3051, 16:831~2999, 18:799~3048, 19:784~3052, 20:831~2999, 22:799~3047, 23:784~3052, 24:832~3000, 26:799~3047, 27:784~3051, 28:832~3000, 30:798~3046, 31:783~3051, 32:832~3000, 34:799~3047, 35:784~3051, 36:832~3000, 38:798~3046, 39:783~3051, 40:831~2999, 42:800~3048, 43:785~3052, 44:832~3000, 46:799~3047, 47:784~3051, 48:833~3001, 50:798~3046, 51:783~3050, 52:832~3000, 54:798~3046, 55:783~3051, 56:833~3001, 58:797~3046, 59:782~3050, 60:832~3000, 62:798~3047, 63:783~3051, 64:832~3000, 66:798~3047, 67:784~3051, 68:832~3000, 70:798~3047, 71:783~3051, 72:831~2999, 74:799~3048, 75:785~3052, 76:831~2999, 78:799~3048, 79:784~3052'
#0:832~3000, 2:799~3047, 3:784~3051, 4:832~3000, 6:799~3047, 7:784~3051, 8:832~3000, 10:799~3047, 11:784~3051, 12:832~3000, 14:798~3047, 15:783~3051, 16:831~2999, 18:799~3048, 19:784~3052, 20:831~2999, 22:799~3047, 23:784~3052, 24:832~3000, 26:799~3047, 27:784~3051, 28:832~3000, 30:798~3046, 31:783~3051, 32:832~3000, 34:799~3047, 35:784~3051, 36:832~3000, 38:798~3046, 39:783~3051, 40:831~2999, 42:800~3048, 43:785~3052, 44:832~3000, 46:799~3047, 47:784~3051, 48:833~3001, 50:798~3046, 51:783~3050, 52:832~3000, 54:798~3046, 55:783~3051, 56:833~3001, 58:797~3046, 59:782~3050, 60:832~3000, 62:798~3047, 63:783~3051, 64:832~3000, 66:798~3047, 67:784~3051, 68:832~3000, 70:798~3047, 71:783~3051, 72:831~2999, 74:799~3048, 75:785~3052, 76:831~2999, 78:799~3048, 79:784~3052
#Averaged continuum dataset saved to J1615_LB_EB0_initcont.ms

# Flagchannels input string for LB_EB1: '0:832~3000, 2:799~3047, 3:784~3051, 4:832~3000, 6:798~3047, 7:783~3051, 8:833~3001, 10:797~3046, 11:782~3050, 12:833~3001, 14:798~3046, 15:783~3050, 16:832~3000, 18:799~3047, 19:784~3051, 20:831~2999, 22:799~3048, 23:784~3052, 24:832~2999, 26:799~3047, 27:784~3052, 28:831~2999, 30:799~3047, 31:784~3052, 32:831~2999, 34:799~3048, 35:784~3052, 36:831~2999, 38:799~3047, 39:784~3052, 40:831~2999, 42:799~3048, 43:784~3052, 44:832~3000, 46:799~3047, 47:784~3051, 48:831~2999, 50:799~3048, 51:784~3052, 52:831~2998, 54:800~3048, 55:785~3053, 56:831~2999, 58:799~3048, 59:784~3052, 60:830~2998, 62:800~3049, 63:785~3053, 64:833~3000, 66:798~3046, 67:783~3050, 68:832~3000, 70:798~3047, 71:783~3051'
#0:832~3000, 2:799~3047, 3:784~3051, 4:832~3000, 6:798~3047, 7:783~3051, 8:833~3001, 10:797~3046, 11:782~3050, 12:833~3001, 14:798~3046, 15:783~3050, 16:832~3000, 18:799~3047, 19:784~3051, 20:831~2999, 22:799~3048, 23:784~3052, 24:832~2999, 26:799~3047, 27:784~3052, 28:831~2999, 30:799~3047, 31:784~3052, 32:831~2999, 34:799~3048, 35:784~3052, 36:831~2999, 38:799~3047, 39:784~3052, 40:831~2999, 42:799~3048, 43:784~3052, 44:832~3000, 46:799~3047, 47:784~3051, 48:831~2999, 50:799~3048, 51:784~3052, 52:831~2998, 54:800~3048, 55:785~3053, 56:831~2999, 58:799~3048, 59:784~3052, 60:830~2998, 62:800~3049, 63:785~3053, 64:833~3000, 66:798~3046, 67:783~3050, 68:832~3000, 70:798~3047, 71:783~3051
#Averaged continuum dataset saved to J1615_LB_EB1_initcont.ms

# Flagchannels input string for LB_EB2: '0:833~3001, 2:797~3046, 3:781~3049'
#0:833~3001, 2:797~3046, 3:781~3049
#Averaged continuum dataset saved to J1615_LB_EB2_initcont.ms
# Flagchannels input string for LB_EB3: '0:833~3001, 2:797~3046, 3:781~3049'
#0:833~3001, 2:797~3046, 3:781~3049
#Averaged continuum dataset saved to J1615_LB_EB3_initcont.ms
# Flagchannels input string for SB_EB0: '0:837~3005, 2:792~3041, 3:789~3057'
#0:837~3005, 2:792~3041, 3:789~3057
#Averaged continuum dataset saved to J1615_SB_EB0_initcont.ms
# Flagchannels input string for SB_EB1: '0:837~3005, 2:792~3041, 3:789~3057'
#0:837~3005, 2:792~3041, 3:789~3057
#Averaged continuum dataset saved to J1615_SB_EB1_initcont.ms
# Flagchannels input string for ACA_EB0: '0:959~3127, 2:921~3170, 3:910~3178'
#0:959~3127, 2:921~3170, 3:910~3178
#Averaged continuum dataset saved to J1615_ACA_EB0_initcont.ms
# Flagchannels input string for ACA_EB1: '0:961~3129, 2:918~3167, 3:915~3183'
#0:961~3129, 2:918~3167, 3:915~3183
#Averaged continuum dataset saved to J1615_ACA_EB1_initcont.ms
# Flagchannels input string for ACA_EB2: '0:962~3130, 2:919~3168, 3:917~3185'
#0:962~3130, 2:919~3168, 3:917~3185
#Averaged continuum dataset saved to J1615_ACA_EB2_initcont.ms

preselfcal_initcont_amp_folder = get_figures_folderpath(
                                  '2_preselfcal_initcont_amp_figures')
make_figures_folder(preselfcal_initcont_amp_folder)

uv_ranges = {'LB':'125~150m','SB':'125~150m','ACA':'0~50m'}

for params in data_params.values():
    vis = prefix+'_'+params['name']+'_initcont.ms'
    baseline_key = params['name'].split('_')[0]
    plotms(vis=vis,
           xaxis='UVdist',
           overwrite=True,
           yaxis='amp',
           coloraxis='spw',
           avgtime='1e8',
           avgscan=True,
           showgui=False,
           plotrange=plotranges[baseline_key],
           plotfile=os.path.join(preselfcal_initcont_amp_folder,
                                 prefix+'_'+params['name']+'_uvdist-v-amp_initcont_preselfcal.png'))

    plotms(vis=vis,
            xaxis='time',
            yaxis='amp',
            avgspw=True,
            uvrange=uv_ranges[baseline_key],
            avgchannel='10000',
            avgbaseline=True,
            coloraxis='corr',
            showgui=False,
            overwrite=True,
            plotfile=os.path.join(preselfcal_initcont_amp_folder,
                                  prefix+'_'+params['name']+'_amp_v_time_initcont_preselfcal.png')
            )


preselfcal_initcont_amp_folder = get_figures_folderpath(
                                  '2_preselfcal_initcont_amp_figures')
make_figures_folder(preselfcal_initcont_amp_folder)

uv_ranges = {'LB':'125~150m','SB':'125~150m','ACA':'0~50m'}

for params in data_params.values():
    vis = prefix+'_'+params['name']+'_initcont.ms'
    baseline_key = params['name'].split('_')[0]
    plotms(vis=vis,
           xaxis='UVdist',
           overwrite=True,
           yaxis='amp',
           coloraxis='spw',
           avgtime='1e8',
           avgscan=True,
           showgui=False,
           plotrange=plotranges[baseline_key],
           plotfile=os.path.join(preselfcal_initcont_amp_folder,
                                 prefix+'_'+params['name']+'_uvdist-v-amp_initcont_preselfcal.png'))

    plotms(vis=vis,
            xaxis='time',
            yaxis='amp',
            avgspw=True,
            uvrange=uv_ranges[baseline_key],
            avgchannel='10000',
            avgbaseline=True,
            coloraxis='corr',
            showgui=False,
            overwrite=True,
            plotfile=os.path.join(preselfcal_initcont_amp_folder,
                                  prefix+'_'+params['name']+'_amp_v_time_initcont_preselfcal.png')
            )

""" Define simple masks and clean scales for imaging """
mask_pa = PA #position angle of mask in degrees
mask_semimajor = 2.7 #semimajor axis of mask in arcsec
mask_semiminor = mask_semimajor*np.cos(incl/180.*np.pi) #semiminor axis of mask in arcsec
mask_ra = '16h15m20.219141s'
mask_dec = '-32.55.05.62585'

mask_TM = f'ellipse[[{mask_ra},{mask_dec}], [{mask_semimajor:.3f}arcsec, {mask_semiminor:.3f}arcsec], {mask_pa:.1f}deg]'
# Cellsize: ~beam/6-7
LB_cellsize =  '0.01arcsec'
# Image size: ~primary beam 1.22*lam/A = 32'' with A=12m (19 arcsec)
LB_imsize = 2000 # primary beam
LB_scales = [0,8,15,30,80]

SB_cellsize =  '0.040arcsec'
SB_imsize = 400 # primary beam
SB_scales = [0,8,15,30]

noise_annulus_TM = f"annulus[[{mask_ra}, {mask_dec}],['4.arcsec', '6.arcsec']]"

mask_semimajor_ACA = 7. #semimajor axis of mask in arcsec
mask_semiminor_ACA = 7. #semiminor axis of mask in arcsec
mask_ACA = f'ellipse[[{mask_ra},{mask_dec}], [{mask_semimajor_ACA:.3f}arcsec, {mask_semiminor_ACA:.3f}arcsec], {mask_pa:.1f}deg]'
# Cellsize: ~beam/6-7, synthesized beam: ~3.3-5'' (ACA)
ACA_cellsize =  '0.4arcsec'
# Image size: ~primary beam 1.22*lam/A = 32'' with A=7m
ACA_imsize = 100 # primary beam
noise_annulus_ACA = f"annulus[[{mask_ra}, {mask_dec}],['10.arcsec', '18.arcsec']]"
#sizes in [arcsec] of the zoomed and overview plots of the output pngs
image_png_plot_sizes = {'LB':[3,10],'ACA':[10,30]}
image_png_plot_sizes['SB'] = image_png_plot_sizes['LB']

preselfcal_images_folder = get_figures_folderpath('3_preselfcal_images')
make_figures_folder(preselfcal_images_folder)

for EB_key,params in data_params_LB.items():
    imagename = prefix+'_'+params['name']+'_initcont_image'
    #clean down to approx 6 sigma
    tclean_wrapper(
                 vis=prefix+'_'+params['name']+'_initcont.ms',
                 imagename=imagename,
                 deconvolver='multiscale',
                 scales=LB_scales,
                 mask=mask_TM,
                 threshold='0.8mJy',
                 cellsize=LB_cellsize,
                 imsize=LB_imsize,
                 parallel=use_parallel,
                 savemodel = 'modelcolumn',
                )
    estimate_SNR(f'{imagename}.image',disk_mask=mask_TM,noise_mask=noise_annulus_TM)
    rms = imstat(imagename = f'{imagename}.image', region = noise_annulus_TM)['rms'][0]
    data_params_LB[EB_key]['rms'] = rms
    generate_image_png(f'{imagename}.image',plot_sizes=image_png_plot_sizes['LB'],
                       color_scale_limits=[-3*rms,10*rms],image_units='ratio',
                       save_folder=preselfcal_images_folder)

#J1615_LB_EB0_initcont_image.image
#Beam 0.110 arcsec x 0.097 arcsec (-73.78 deg)
#Flux inside disk mask: 317.10 mJy
#Peak intensity of source: 6.76 mJy/beam
#rms: 7.29e-02 mJy/beam
#Peak SNR: 92.76
#J1615_LB_EB1_initcont_image.image
#Beam 0.128 arcsec x 0.100 arcsec (87.78 deg)
#Flux inside disk mask: 336.66 mJy
#Peak intensity of source: 8.08 mJy/beam
#rms: 1.26e-01 mJy/beam
#Peak SNR: 64.09
#J1615_LB_EB2_initcont_image.image
#Beam 0.198 arcsec x 0.166 arcsec (69.23 deg)
#Flux inside disk mask: 354.45 mJy
#Peak intensity of source: 19.25 mJy/beam
#rms: 1.52e-01 mJy/beam
#Peak SNR: 127.08
#J1615_LB_EB3_initcont_image.image
#Beam 0.187 arcsec x 0.168 arcsec (78.16 deg)
#Flux inside disk mask: 351.01 mJy
#Peak intensity of source: 17.33 mJy/beam
#rms: 1.45e-01 mJy/beam
#Peak SNR: 119.39


for EB_key,params in data_params_SB.items():
    imagename = prefix+'_'+params['name']+'_initcont_image'
    #clean down to 6 sigma
    tclean_wrapper(
                 vis=prefix+'_'+params['name']+'_initcont.ms',
                 imagename=imagename,
                 deconvolver='multiscale',
                 scales=SB_scales,
                 mask=mask_TM,
                 threshold='6.2mJy',
                 cellsize=SB_cellsize,
                 imsize=SB_imsize,
                 parallel=use_parallel,
                 savemodel = 'modelcolumn',
                )
    estimate_SNR(f'{imagename}.image',disk_mask=mask_TM,noise_mask=noise_annulus_TM)
    rms = imstat(imagename = f'{imagename}.image', region = noise_annulus_TM)['rms'][0]
    data_params_SB[EB_key]['rms'] = rms
    generate_image_png(f'{imagename}.image',plot_sizes=image_png_plot_sizes['SB'],
                       color_scale_limits=[-3*rms,10*rms],
                       save_folder=preselfcal_images_folder)
#J1615_SB_EB0_initcont_image.image
#Beam 0.530 arcsec x 0.438 arcsec (-89.63 deg)
#Flux inside disk mask: 327.23 mJy
#Peak intensity of source: 89.14 mJy/beam
#rms: 1.03e+00 mJy/beam
#Peak SNR: 86.14
#J1615_SB_EB1_initcont_image.image
#Beam 0.543 arcsec x 0.445 arcsec (-77.13 deg)
#Flux inside disk mask: 347.50 mJy
#Peak intensity of source: 93.81 mJy/beam
#rms: 9.05e-01 mJy/beam
#Peak SNR: 103.63

for EB_key,params in data_params_ACA.items():
    imagename = prefix+'_'+params['name']+'_initcont_image'
    #clean down to 6 sigma
    tclean_wrapper(
                 vis=prefix+'_'+params['name']+'_initcont.ms',
                 imagename=imagename,
                 deconvolver='hogbom',
                 mask=mask_ACA,
                 threshold='36mJy',
                 cellsize=ACA_cellsize,
                 imsize=ACA_imsize,
                 parallel=use_parallel,
                 savemodel = 'modelcolumn',
                )
    estimate_SNR(f'{imagename}.image', disk_mask = mask_ACA, noise_mask = noise_annulus_ACA)
    rms = imstat(imagename = f'{imagename}.image', region = noise_annulus_ACA)['rms'][0]
    data_params_ACA[EB_key]['rms'] = rms
    generate_image_png(f'{imagename}.image',plot_sizes=image_png_plot_sizes['ACA'],
                       color_scale_limits=[-3*rms,10*rms],
                       save_folder=preselfcal_images_folder)

#J1615_ACA_EB0_initcont_image.image
#Beam 5.001 arcsec x 3.303 arcsec (-86.09 deg)
#Flux inside disk mask: 400.21 mJy
#Peak intensity of source: 353.83 mJy/beam
#rms: 4.86e+00 mJy/beam
#Peak SNR: 72.77
#J1615_ACA_EB1_initcont_image.image
#Beam 4.684 arcsec x 2.987 arcsec (-83.69 deg)
#Flux inside disk mask: 349.34 mJy
#Peak intensity of source: 312.70 mJy/beam
#rms: 5.13e+00 mJy/beam
#Peak SNR: 60.97
#J1615_ACA_EB2_initcont_image.image
#Beam 4.799 arcsec x 2.928 arcsec (88.64 deg)
#Flux inside disk mask: 338.06 mJy
#Peak intensity of source: 344.87 mJy/beam
#rms: 2.96e+00 mJy/beam
#Peak SNR: 116.36


######
# SELF-CAL INDIVIDUAL EBs
######
""" Self-calibration parameters """
single_EB_contspws = '0~3'

single_EB_spw_mapping = [0,0,0,0]

EB_selfcal_shift_folder = get_figures_folderpath(
                 '4_individual_EB_selfcal_and_shift_figures')
make_figures_folder(EB_selfcal_shift_folder)

# for ACA data
for params in data_params_ACA.values():
    single_EB_p1 = prefix+'_'+params['name']+'_initcont.p1'
    os.system('rm -rf '+single_EB_p1)
    gaincal(vis=prefix+'_'+params['name']+'_initcont.ms',caltable=single_EB_p1,
        gaintype='T', spw=single_EB_contspws,combine='scan,spw',
        calmode='p', solint='inf', minsnr=4., minblperant=3)

    """ Print calibration png file """
    plotms(single_EB_p1,
           xaxis='time',
           yaxis='GainPhase',
           overwrite=True,
           showgui=False,
           plotfile=os.path.join(EB_selfcal_shift_folder,
                                 prefix+'_'+params['name']+'_initcont_gain_p1_phase_vs_time.png'))

    """ Apply the solutions """
    applycal(vis=prefix+'_'+params['name']+'_initcont.ms', spw=single_EB_contspws,spwmap=single_EB_spw_mapping,
        gaintable=[single_EB_p1], interp='linearPD', applymode='calonly', calwt=True)
    split(vis=prefix+'_'+params['name']+'_initcont.ms',
          outputvis=prefix+'_'+params['name']+'_initcont_selfcal.ms',
          datacolumn='corrected')

# for SB data 
for params in data_params_SB.values():
    single_EB_p1 = prefix+'_'+params['name']+'_initcont.p1'
    os.system('rm -rf '+single_EB_p1)
    gaincal(vis=prefix+'_'+params['name']+'_initcont.ms',caltable=single_EB_p1,
        gaintype='T', spw=single_EB_contspws,combine='scan,spw',
        calmode='p', solint='inf', minsnr=4., minblperant=3)

    """ Print calibration png file """
    plotms(single_EB_p1,
           xaxis='time',
           yaxis='GainPhase',
           overwrite=True,
           showgui=False,
           plotfile=os.path.join(EB_selfcal_shift_folder,
                                 prefix+'_'+params['name']+'_initcont_gain_p1_phase_vs_time.png'))

    """ Apply the solutions """
    applycal(vis=prefix+'_'+params['name']+'_initcont.ms', spw=single_EB_contspws,spwmap=single_EB_spw_mapping,
        gaintable=[single_EB_p1], interp='linearPD', applymode='calonly', calwt=True)
    split(vis=prefix+'_'+params['name']+'_initcont.ms',
          outputvis=prefix+'_'+params['name']+'_initcont_selfcal.ms',
          datacolumn='corrected')


# LB EB0 has 80 spws
single_EB0_spw_mapping_LB = np.zeros(80)
single_EB0_contspws_LB = '0~79'

single_EB0_p1 = prefix+'_'+'LB_EB0'+'_initcont.p1'
os.system('rm -rf '+single_EB0_p1)
gaincal(vis=prefix+'_'+'LB_EB0'+'_initcont.ms',caltable=single_EB0_p1,
    gaintype='T', spw=single_EB0_contspws_LB,combine='scan,spw',
    calmode='p', solint='inf', minsnr=4., minblperant=3)
#1 of 42 solutions flagged due to SNR < 4 in spw=0 at 2022/07/25/23:57:28.2

""" Print calibration png file """
plotms(single_EB0_p1,
       xaxis='time',
       yaxis='GainPhase',
       overwrite=True,
       showgui=False,
       plotfile=os.path.join(EB_selfcal_shift_folder,
                             prefix+'_'+'LB_EB0'+'_initcont_gain_p1_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=prefix+'_'+'LB_EB0'+'_initcont.ms', spw=single_EB0_contspws_LB,spwmap=single_EB0_spw_mapping_LB,
    gaintable=[single_EB0_p1], interp='linearPD', applymode='calonly', calwt=True)
split(vis=prefix+'_'+'LB_EB0'+'_initcont.ms',
      outputvis=prefix+'_'+'LB_EB0'+'_initcont_selfcal.ms',
      datacolumn='corrected')

# LB EB1 has 72 spws
single_EB1_spw_mapping_LB = np.zeros(72)
single_EB1_contspws_LB = '0~71'

single_EB1_p1 = prefix+'_'+'LB_EB1'+'_initcont.p1'
os.system('rm -rf '+single_EB1_p1)
gaincal(vis=prefix+'_'+'LB_EB1'+'_initcont.ms',caltable=single_EB1_p1,
    gaintype='T', spw=single_EB1_contspws_LB,combine='scan,spw',
    calmode='p', solint='inf', minsnr=4., minblperant=3)

""" Print calibration png file """
plotms(single_EB1_p1,
       xaxis='time',
       yaxis='GainPhase',
       overwrite=True,
       showgui=False,
       plotfile=os.path.join(EB_selfcal_shift_folder,
                             prefix+'_'+'LB_EB1'+'_initcont_gain_p1_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=prefix+'_'+'LB_EB1'+'_initcont.ms', spw=single_EB1_contspws_LB,spwmap=single_EB1_spw_mapping_LB,
    gaintable=[single_EB1_p1], interp='linearPD', applymode='calonly', calwt=True)
split(vis=prefix+'_'+'LB_EB1'+'_initcont.ms',
      outputvis=prefix+'_'+'LB_EB1'+'_initcont_selfcal.ms',
      datacolumn='corrected')

# LB EB2 has 4 spw
single_EB2_spw_mapping_LB = np.zeros(4)
single_EB2_contspws_LB = '0~3'

single_EB2_p1 = prefix+'_'+'LB_EB2'+'_initcont.p1'
os.system('rm -rf '+single_EB2_p1)
gaincal(vis=prefix+'_'+'LB_EB2'+'_initcont.ms',caltable=single_EB2_p1,
    gaintype='T', spw=single_EB2_contspws_LB,combine='scan,spw',
    calmode='p', solint='inf', minsnr=4., minblperant=3)

""" Print calibration png file """
plotms(single_EB2_p1,
       xaxis='time',
       yaxis='GainPhase',
       overwrite=True,
       showgui=False,
       plotfile=os.path.join(EB_selfcal_shift_folder,
                             prefix+'_'+'LB_EB2'+'_initcont_gain_p1_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=prefix+'_'+'LB_EB2'+'_initcont.ms', spw=single_EB2_contspws_LB,spwmap=single_EB2_spw_mapping_LB,
    gaintable=[single_EB2_p1], interp='linearPD', applymode='calonly', calwt=True)
split(vis=prefix+'_'+'LB_EB2'+'_initcont.ms',
      outputvis=prefix+'_'+'LB_EB2'+'_initcont_selfcal.ms',
      datacolumn='corrected')

# special case for LB data since we have 4 spws in EB3.
single_EB3_spw_mapping_LB = np.zeros(4)
single_EB3_contspws_LB = '0~3'

single_EB3_p1 = prefix+'_'+'LB_EB3'+'_initcont.p1'
os.system('rm -rf '+single_EB3_p1)
gaincal(vis=prefix+'_'+'LB_EB3'+'_initcont.ms',caltable=single_EB3_p1,
    gaintype='T', spw=single_EB3_contspws_LB,combine='scan,spw',
    calmode='p', solint='inf', minsnr=4., minblperant=3)

""" Print calibration png file """
plotms(single_EB3_p1,
       xaxis='time',
       yaxis='GainPhase',
       overwrite=True,
       showgui=False,
       plotfile=os.path.join(EB_selfcal_shift_folder,
                             prefix+'_'+'LB_EB3'+'_initcont_gain_p1_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=prefix+'_'+'LB_EB3'+'_initcont.ms', spw=single_EB3_contspws_LB,spwmap=single_EB3_spw_mapping_LB,
    gaintable=[single_EB3_p1], interp='linearPD', applymode='calonly', calwt=True)
split(vis=prefix+'_'+'LB_EB3'+'_initcont.ms',
      outputvis=prefix+'_'+'LB_EB3'+'_initcont_selfcal.ms',
      datacolumn='corrected')


### Image self-cal'd EBs ###
######### LB 
for params in data_params_LB.values():
    imagename = prefix+'_'+params['name']+'_initcont_selfcal_image'
    tclean_wrapper(
                 vis=prefix+'_'+params['name']+'_initcont_selfcal.ms',
                 imagename=imagename,
                 deconvolver='multiscale',
                 scales=LB_scales,
                 mask=mask_TM,
                 threshold='0.5mJy',
                 cellsize=LB_cellsize,
                 imsize=LB_imsize,
                 parallel=use_parallel,
                )
    estimate_SNR(f'{imagename}.image',disk_mask=mask_TM,noise_mask=noise_annulus_TM)
    rms = params['rms']
    generate_image_png(f'{imagename}.image',plot_sizes=image_png_plot_sizes['LB'],
                       color_scale_limits=[-3*rms,10*rms],
                       save_folder=EB_selfcal_shift_folder)


#J1615_LB_EB0_initcont_selfcal_image.image
#Beam 0.110 arcsec x 0.097 arcsec (-73.78 deg)
#Flux inside disk mask: 326.58 mJy
#Peak intensity of source: 6.81 mJy/beam
#rms: 6.12e-02 mJy/beam
#Peak SNR: 111.27
#J1615_LB_EB1_initcont_selfcal_image.image
#Beam 0.128 arcsec x 0.100 arcsec (87.78 deg)
#Flux inside disk mask: 353.70 mJy
#Peak intensity of source: 8.40 mJy/beam
#rms: 7.64e-02 mJy/beam
#Peak SNR: 110.02
#J1615_LB_EB2_initcont_selfcal_image.image
#Beam 0.198 arcsec x 0.166 arcsec (69.23 deg)
#Flux inside disk mask: 366.21 mJy
#Peak intensity of source: 19.49 mJy/beam
#rms: 7.39e-02 mJy/beam
#Peak SNR: 263.81
#J1615_LB_EB3_initcont_selfcal_image.image
#Beam 0.187 arcsec x 0.168 arcsec (78.16 deg)
#Flux inside disk mask: 361.60 mJy
#Peak intensity of source: 17.58 mJy/beam
#rms: 8.68e-02 mJy/beam
#Peak SNR: 202.62

## Compute intensity ratio to check position shifts between different LB EBs before
#applying alignment
default(immath)
for params in data_params_LB.values():
    ref_image = prefix+'_LB_EB0_initcont_selfcal_image.image'
    imagename = prefix+'_'+params['name']+'_initcont_selfcal_image'
    os.system('rm -rf '+imagename+'.ratio')
    immath(imagename=[ref_image,imagename+'.image'],mode='evalexpr',
           outfile=imagename+'.ratio',
           expr='iif(IM0 > 3*'+str(data_params_LB['LB0']['rms'])+', IM1/IM0, 0)'
           )
    generate_image_png(f'{imagename}.ratio',plot_sizes=[2*mask_semimajor,2*mask_semimajor],
                       color_scale_limits=[0.5,1.5],image_units='ratio',
                       save_folder=EB_selfcal_shift_folder)

######### SB 
for params in data_params_SB.values():
    imagename = prefix+'_'+params['name']+'_initcont_selfcal_image'
    tclean_wrapper(
                 vis=prefix+'_'+params['name']+'_initcont_selfcal.ms',
                 imagename=imagename,
                 deconvolver='multiscale',
                 scales=SB_scales,
                 mask=mask_TM,
                 threshold='0.8mJy',
                 cellsize=SB_cellsize,
                 imsize=SB_imsize,
                 parallel=use_parallel,
                )
    estimate_SNR(f'{imagename}.image',disk_mask=mask_TM,noise_mask=noise_annulus_TM)
    rms = params['rms']
    generate_image_png(f'{imagename}.image',plot_sizes=image_png_plot_sizes['SB'],
                       color_scale_limits=[-3*rms,10*rms],
                       save_folder=EB_selfcal_shift_folder)


#J1615_SB_EB0_initcont_selfcal_image.image
#Beam 0.530 arcsec x 0.438 arcsec (-89.63 deg)
#Flux inside disk mask: 382.11 mJy
#Peak intensity of source: 100.32 mJy/beam
#rms: 1.14e-01 mJy/beam
#Peak SNR: 883.50
#J1615_SB_EB1_initcont_selfcal_image.image
#Beam 0.543 arcsec x 0.445 arcsec (-77.13 deg)
#Flux inside disk mask: 387.63 mJy
#Peak intensity of source: 104.01 mJy/beam
#rms: 1.30e-01 mJy/beam
#Peak SNR: 801.39


## Compute intensity ratio to check position shifts between differnet SB EBs before applying alignment
default(immath)
for params in data_params_SB.values():
    ref_image = prefix+'_SB_EB0_initcont_selfcal_image.image'
    imagename = prefix+'_'+params['name']+'_initcont_selfcal_image'
    os.system('rm -rf '+imagename+'.ratio')
    immath(imagename=[ref_image,imagename+'.image'],mode='evalexpr',
           outfile=imagename+'.ratio',
           expr='iif(IM0 > 3*'+str(data_params_SB['SB0']['rms'])+', IM1/IM0, 0)')
    generate_image_png(f'{imagename}.ratio',
                       plot_sizes=[2*mask_semimajor,2*mask_semimajor],
                       color_scale_limits=[0.5,1.5],image_units='ratio',
                       save_folder=EB_selfcal_shift_folder)


########## ACA 
for params in data_params_ACA.values():
    imagename = prefix+'_'+params['name']+'_initcont_selfcal_image'
    tclean_wrapper(
                 vis=prefix+'_'+params['name']+'_initcont_selfcal.ms',
                 imagename=imagename,
                 deconvolver='hogbom',
                 mask=mask_ACA,
                 threshold='36mJy',
                 cellsize=ACA_cellsize,
                 imsize=ACA_imsize,
                 parallel=use_parallel,
                )
    estimate_SNR(f'{imagename}.image', disk_mask = mask_ACA, noise_mask = noise_annulus_ACA)
    rms = params['rms']
    generate_image_png(f'{imagename}.image',plot_sizes=image_png_plot_sizes['ACA'],
                       color_scale_limits=[-3*rms,10*rms],
                       save_folder=EB_selfcal_shift_folder)

#J1615_ACA_EB0_initcont_selfcal_image.image
#Beam 5.001 arcsec x 3.303 arcsec (-86.09 deg)
#Flux inside disk mask: 395.29 mJy
#Peak intensity of source: 354.78 mJy/beam
#rms: 5.02e+00 mJy/beam
#Peak SNR: 70.74
#J1615_ACA_EB1_initcont_selfcal_image.image
#Beam 4.684 arcsec x 2.987 arcsec (-83.69 deg)
#Flux inside disk mask: 351.70 mJy
#Peak intensity of source: 314.71 mJy/beam
#rms: 4.11e+00 mJy/beam
#Peak SNR: 76.50
#J1615_ACA_EB2_initcont_selfcal_image.image
#Beam 4.799 arcsec x 2.928 arcsec (88.64 deg)
#Flux inside disk mask: 338.16 mJy
#Peak intensity of source: 345.47 mJy/beam
#rms: 2.47e+00 mJy/beam
#Peak SNR: 140.05

## Compute intensity ratio to check position shifts between differnet ACA EBs before applying alignment
default(immath)
for params in data_params_ACA.values():
    ref_image = prefix+'_ACA_EB0_initcont_selfcal_image.image'
    imagename = prefix+'_'+params['name']+'_initcont_selfcal_image'
    os.system('rm -rf '+imagename+'.ratio')
    immath(imagename=[ref_image,imagename+'.image'],mode='evalexpr',
           outfile=imagename+'.ratio',
           expr='iif(IM0 > 3*'+str(data_params_ACA['ACA0']['rms'])+', IM1/IM0, 0)'
           )
    generate_image_png(f'{imagename}.ratio',
                       plot_sizes=[2*mask_semimajor_ACA,2*mask_semimajor_ACA],
                       color_scale_limits=[0.5,1.5],image_units='ratio',
                       save_folder=EB_selfcal_shift_folder)


######
# ALIGN DATA (go from *initcont_selfcal.ms to *initcont_shift.ms)
######

# Select the LB EB to act as the reference (usually the best SNR one).
# In this case, LB EB2 has been picked because it has good snr, and elevation during observations was good
# thus beam is not too elliptical

reference_for_LB_alignment = f'{prefix}_LB_EB2_initcont_selfcal.ms'
assert 'LB' in reference_for_LB_alignment, 'you need to choose an LB EB for alignment of LB'

alignment_offsets = {}

# All the other EBs will be aligned to the reference_EB
# We also include the reference_EB itself to make sure the coordinate changes are
# copied over.

offset_LB_EBs = ['{}_{}_initcont_selfcal.ms'.format(prefix, params['name'])
                 for params in data_params_LB.values()]

#select the continuum spw with the large bandwidth
continuum_spw_id = 1
# Find the relative offsets and update the phase centers for all offset_EBs.
npix = 1024
cell_size = 0.01
alignment.align_measurement_sets(reference_ms=reference_for_LB_alignment,
                                 align_ms=offset_LB_EBs,npix=npix,cell_size=cell_size,
                                 spwid=continuum_spw_id)

#New coordinates for J1615_LB_EB0_initcont_selfcal.ms
#requires a shift of [0.015176,0.029065]
#New coordinates for J1615_LB_EB1_initcont_selfcal.ms
#requires a shift of [-0.029851,-0.027532]
#New coordinates for J1615_LB_EB2_initcont_selfcal.ms
#no shift, reference MS.
#New coordinates for J1615_LB_EB3_initcont_selfcal.ms
#requires a shift of [-0.016376,0.0068062]

"""
We comment this out since we realize later that LB1 is not good
We copy everything, but we change LB1 below
alignment_offsets['LB_EB0'] = [0.015176,0.029065] 
alignment_offsets['LB_EB1'] = [-0.029851,-0.027532]
alignment_offsets['LB_EB2'] = [0,0] #ref EB
alignment_offsets['LB_EB3'] = [-0.016376,0.0068062]
"""

shifted_LB_EBs = [EB.replace('.ms','_shift.ms') for EB in offset_LB_EBs]


#to check if alignment worked, calculate shift again and verify that shifts are small (i.e.
#a fraction of the cell size)
#however, we have to use ms with the same frame
for shifted_ms in shifted_LB_EBs:
    if shifted_ms == reference_for_LB_alignment.replace('.ms','_shift.ms'):
        #skip the reference because the fitter will fails for unknown reason
        continue
    offset = alignment.find_offset(reference_ms=reference_for_LB_alignment,
                                   offset_ms=shifted_ms,npix=npix,cell_size=cell_size,
                                   spwid=continuum_spw_id)
    print(f'#offset for {shifted_ms}: ',offset)
#things have been shifted consistently with script
#offset for J1615_LB_EB0_initcont_selfcal_shift.ms:  [0.00030264 0.00124152]
#offset for J1615_LB_EB1_initcont_selfcal_shift.ms:  [-0.00091492  0.0002146 ]
#offset for J1615_LB_EB3_initcont_selfcal_shift.ms:  [-0.00029109 -0.00010335]

"""
Check what's going on with LB EB1
npix = 1024
cell_size = 0.01

offset = alignment.find_offset(reference_ms='J1615_LB_EB0_initcont_shift.ms',
                               offset_ms='J1615_LB_EB1_initcont_shift.ms',npix=npix,cell_size=cell_size,
                               spwid=1)
print('#offset for LB EB1: ',offset)
"""

# Merge shifted LB EBs for aligning SB EBs
LB_concat_shifted = f'{prefix}_LB_concat_shifted.ms'
os.system(f'rm -rf {LB_concat_shifted}')
concat(vis=shifted_LB_EBs,concatvis=LB_concat_shifted,dirtol='0.1arcsec',
       copypointing=False)


# Align SB EBs to concat shifted LB EBs
reference_for_SB_alignment = LB_concat_shifted

offset_SB_EBs = ['{}_{}_initcont_selfcal.ms'.format(prefix, params['name'])
                 for params in data_params_SB.values()]

alignment.align_measurement_sets(reference_ms=reference_for_SB_alignment,
                                 align_ms=offset_SB_EBs,npix=npix,cell_size=cell_size,
                                 spwid=continuum_spw_id)

#New coordinates for J1615_SB_EB0_initcont_selfcal.ms
#requires a shift of [-0.034532,-0.022261]
#New coordinates for J1615_SB_EB1_initcont_selfcal.ms
#requires a shift of [-0.038019,-0.055824]


alignment_offsets['SB_EB0'] = [-0.034532,-0.022261]
alignment_offsets['SB_EB1'] = [-0.038019,-0.055824]


shifted_SB_EBs = [EB.replace('.ms','_shift.ms') for EB in offset_SB_EBs]

#check by calculating offset again
for shifted_ms in shifted_SB_EBs:
    offset = alignment.find_offset(reference_ms=reference_for_SB_alignment,
                                   offset_ms=shifted_ms,npix=npix,cell_size=cell_size,
                                   spwid=continuum_spw_id)
    print(f'#offset for {shifted_ms}: ',offset)

#offset for J1615_SB_EB0_initcont_selfcal_shift.ms:  [-0.00095835 -0.00089889]
#offset for J1615_SB_EB1_initcont_selfcal_shift.ms:  [-0.00037685 -0.00290701]

# Merge shifted SB EBs for aligning ACA EBs
SB_concat_shifted = prefix+'_SB_concat_shifted.ms'
os.system('rm -rf '+SB_concat_shifted)
concat(vis=shifted_SB_EBs,concatvis=SB_concat_shifted,dirtol='0.1arcsec',
       copypointing=False)

# Align ACA EBs to concat shifted SB EBs
reference_for_ACA_alignment = SB_concat_shifted

offset_ACA_EBs = ['{}_{}_initcont_selfcal.ms'.format(prefix, params['name'])
                  for params in data_params_ACA.values()]

#changing values of npix and cell_size for ACA 
npix_ACA = 32
cell_size_ACA = 0.5

alignment.align_measurement_sets(reference_ms=reference_for_ACA_alignment,
                                 align_ms=offset_ACA_EBs,npix=npix_ACA,
                                 cell_size=cell_size_ACA,spwid=continuum_spw_id)


#New coordinates for J1615_ACA_EB0_initcont_selfcal.ms
#requires a shift of [-0.095162,0.012366]
#New coordinates for J1615_ACA_EB1_initcont_selfcal.ms
#requires a shift of [0.0904,-0.039708]
#New coordinates for J1615_ACA_EB2_initcont_selfcal.ms
#requires a shift of [0.080111,-0.0047152]

alignment_offsets['ACA_EB0'] = [-0.095162,0.012366]
alignment_offsets['ACA_EB1'] = [0.0904,-0.039708]
alignment_offsets['ACA_EB2'] = [0.080111,-0.0047152]

shifted_ACA_EBs = [EB.replace('.ms','_shift.ms') for EB in offset_ACA_EBs]

#check by calculating offset again
for shifted_ms in shifted_ACA_EBs:
    offset = alignment.find_offset(reference_ms=reference_for_ACA_alignment,
                                   offset_ms=shifted_ms,npix=npix_ACA,cell_size=cell_size_ACA,
                                   spwid=continuum_spw_id)
    print(f'#offset for {shifted_ms}: ',offset)
#offset for J1615_ACA_EB0_initcont_selfcal_shift.ms:  [-0.00117271 -0.00071151]
#offset for J1615_ACA_EB1_initcont_selfcal_shift.ms:  [ 0.01568197 -0.00232143]
#offset for J1615_ACA_EB2_initcont_selfcal_shift.ms:  [0.0174189 0.0039384]


"""
EB LB1 looks offset. We split individual EBs and concat them back with freqtool to have
more snr in getting the right alignment.
"""

scans_LB_EB1 = ['65','67','70','73','77','80','83','86','90','93','96','99','103','106','109','112','116','119']
for i in np.arange(len(scans_LB_EB1)):
    split(vis='J1615_LB_EB1_initcont_selfcal.ms',outputvis='J1615_LB_EB1_initcont_selfcal_scan'+scans_LB_EB1[i]+'.ms',scan=scans_LB_EB1[i],datacolumn='data')

LB_EB1_to_concat = ['J1615_LB_EB1_initcont_selfcal_scan'+scans_LB_EB1[i]+'.ms' for i in np.arange(len(scans_LB_EB1))]

os.system('rm -rf J1615_LB_EB1_initcont_selfcal_pseudo_cont.ms')
concat(vis=LB_EB1_to_concat,concatvis='J1615_LB_EB1_initcont_selfcal_pseudo_cont.ms',
      dirtol='0.1arcsec',freqtol = '50MHz',copypointing=False)

os.system('du -hs *LB_EB1*shift*')
os.system('rm -rf *LB_EB1*shift*')

offset_EB_LB1 = alignment.find_offset(reference_ms=reference_for_LB_alignment,
                               offset_ms='J1615_LB_EB1_initcont_selfcal_pseudo_cont.ms',npix=npix,cell_size=cell_size,
                               spwid=continuum_spw_id)
#New coordinates for J1615_LB_EB1_initcont_selfcal_pseudo_cont.ms
#requires a shift of [-0.01610431,0.01358796]

alignment_offsets['LB_EB0'] = [0.015176,0.029065] 
alignment_offsets['LB_EB1'] = [-0.01610431,0.01358796]
alignment_offsets['LB_EB2'] = [0,0] #ref EB
alignment_offsets['LB_EB3'] = [-0.016376,0.0068062]

alignment.align_measurement_sets(
        reference_ms=reference_for_LB_alignment,align_ms=['J1615_LB_EB1_initcont_selfcal.ms'],
        align_offsets=[alignment_offsets['LB_EB1']],npix=None,cell_size=None)


# Remove the '_selfcal' part of the names to match the naming convention below.
for shifted_EB in shifted_LB_EBs+shifted_SB_EBs+shifted_ACA_EBs:
    os.system('mv {} {}'.format(shifted_EB, shifted_EB.replace('_selfcal', '')))


""" Check that the images are indeed aligned after the shift """
for params in data_params_LB.values():
    imagename = prefix+'_'+params['name']+'_initcont_shift_image'
    tclean_wrapper(
                   vis=prefix+'_'+params['name']+'_initcont_shift.ms',
                   imagename=imagename,
                   deconvolver='multiscale',
                   scales=LB_scales,
                   mask=mask_TM,
                   threshold='0.5mJy',
                   cellsize=LB_cellsize,
                   imsize=LB_imsize,
                   parallel=use_parallel,
                  )
    estimate_SNR(f'{imagename}.image',disk_mask=mask_TM,
                 noise_mask=noise_annulus_TM)
    rms = params['rms']
    generate_image_png(f'{imagename}.image',plot_sizes=image_png_plot_sizes['LB'],
                       color_scale_limits=[-3*rms,10*rms],
                       save_folder=EB_selfcal_shift_folder)

## Compute intensity ratio between aligned images from LB EBs
default(immath)
for params in data_params_LB.values():
    ref_image = prefix+'_LB_EB0_initcont_shift_image.image'
    imagename = prefix+'_'+params['name']+'_initcont_shift_image'
    os.system('rm -rf '+imagename+'.ratio')
    immath(imagename=[ref_image,imagename+'.image'],mode='evalexpr',
           outfile=imagename+'.ratio',
           expr='iif(IM0 > 3*'+str(data_params_LB['LB0']['rms'])+', IM1/IM0, 0)'
           )
    generate_image_png(f'{imagename}.ratio',
                       plot_sizes=[2*mask_semimajor,2*mask_semimajor],
                       color_scale_limits=[0.5,1.5],image_units='ratio',
                       save_folder=EB_selfcal_shift_folder)

for params in data_params_SB.values():
    imagename = prefix+'_'+params['name']+'_initcont_shift_image'
    tclean_wrapper(
                   vis=prefix+'_'+params['name']+'_initcont_shift.ms',
                   imagename=imagename,
                   deconvolver='multiscale',
                   scales=SB_scales,
                   mask=mask_TM,
                   threshold='6mJy',
                   cellsize=SB_cellsize,
                   imsize=SB_imsize,
                   parallel=use_parallel,
                  )
    estimate_SNR(f'{imagename}.image',disk_mask=mask_TM,
                 noise_mask=noise_annulus_TM)
    rms = params['rms']
    generate_image_png(f'{imagename}.image',plot_sizes=image_png_plot_sizes['SB'],
                       color_scale_limits=[-3*rms,10*rms],
                       save_folder=EB_selfcal_shift_folder)

## Compute intensity ratio between aligned images from SB EBs
default(immath)
for params in data_params_SB.values():
    ref_image = prefix+'_SB_EB0_initcont_shift_image.image'
    imagename = prefix+'_'+params['name']+'_initcont_shift_image'
    os.system('rm -rf '+imagename+'.ratio')
    immath(imagename=[ref_image,imagename+'.image'],mode='evalexpr',
           outfile=imagename+'.ratio',
           expr='iif(IM0 > 3*'+str(data_params_SB['SB0']['rms'])+', IM1/IM0, 0)'
           )
    generate_image_png(f'{imagename}.ratio',
                       plot_sizes=[2*mask_semimajor,2*mask_semimajor],
                       color_scale_limits=[0.5,1.5],image_units='ratio',
                       save_folder=EB_selfcal_shift_folder)


for params in data_params_ACA.values():
    imagename = prefix+'_'+params['name']+'_initcont_shift_image'
    tclean_wrapper(
                 vis=prefix+'_'+params['name']+'_initcont_shift.ms',
                 imagename=imagename,
                 deconvolver='hogbom',
                 mask=mask_ACA,
                 threshold='50mJy',
                 cellsize=ACA_cellsize,
                 imsize=ACA_imsize,
                 parallel=use_parallel,
                )
    estimate_SNR(f'{imagename}.image', disk_mask = mask_ACA, noise_mask = noise_annulus_ACA)
    rms = params['rms']
    generate_image_png(f'{imagename}.image',plot_sizes=image_png_plot_sizes['ACA'],
                       color_scale_limits=[-3*rms,10*rms],
                       save_folder=EB_selfcal_shift_folder)

## Compute intensity ratio between aligned images from ACA EBs
default(immath)
for params in data_params_ACA.values():
    ref_image = prefix+'_ACA_EB0_initcont_shift_image.image'
    imagename = prefix+'_'+params['name']+'_initcont_shift_image'
    os.system('rm -rf '+imagename+'.ratio')
    immath(imagename=[ref_image,imagename+'.image'],mode='evalexpr',
           outfile=imagename+'.ratio',
           expr='iif(IM0 > 3*'+str(data_params_ACA['ACA0']['rms'])+', IM1/IM0, 0)'
           )
    generate_image_png(f'{imagename}.ratio',
                       plot_sizes=[2*mask_semimajor_ACA,2*mask_semimajor_ACA],
                       color_scale_limits=[0.5,1.5],image_units='ratio',
                       save_folder=EB_selfcal_shift_folder)


""" Now that everything is aligned, we inspect the flux calibration. """

for params in data_params.values():
    msfile = prefix+'_'+params['name']+'_initcont_shift.ms'
    export_MS(msfile) #export MS contents into Numpy save files


""" Plot deprojected visibility profiles for all data together """
list_npz_files = []
for baseline_key,n_EB in number_of_EBs.items():
    list_npz_files += [f'{prefix}_{baseline_key}_EB{i}_initcont_shift.vis.npz'
                       for i in range(n_EB)]

deprojected_vis_profiles_folder = get_figures_folderpath('5_deprojected_vis_profiles')
make_figures_folder(deprojected_vis_profiles_folder)

plot_deprojected(filelist=list_npz_files,
                 fluxscale=[1.]*(number_of_EBs['LB']+number_of_EBs['SB']+number_of_EBs['ACA']),PA=PA,incl=incl,show_err=True,
                 plot_label=os.path.join(deprojected_vis_profiles_folder,
                                         prefix+'_flux_scale_EB_preselfcal.png'))


flux_comparison_folder = get_figures_folderpath('6_flux_comparisons')
make_figures_folder(flux_comparison_folder)

"""

SB has overlapping uv ranges with both ACA and LB, so
we select an SB EB as the reference for flux scaling.

In case this source does not have ACA data, simply ignore the ACA steps in the list below.
 
If all SB EBs suffer from decoherence and cannot be used, see below

We correct flux differences >4%, if phase noise looks reasonable

If you need to re-scale fluxes, use command:
rescale_flux(vis=prefix+'_LB_EB0_initcont_shift.ms', gencalparameter=[1.044])

The general procedure is as follows:
1) check flux scaling, and if flux differences are >4%, re-scale the fluxes unless
    there is clear de-coherence (e.g. seen as a systematic decrease of scaling with UV distance)
2) do not scale those EBs with phase decoherence. Proceed with self-cal following the steps below 
   to the point that those EBs are self calibrated
3) check flux scaling again
4) if no flux scaling has been applied in 1), and you now still see a flux offset, then
    apply the flux scaling determined in step 3) to the non-self caled EBs
    and repeat the self-cal

If all SB EBs suffer from phase decoherence and cannot be used as the reference
for flux scaling:
1) concat ACA data and self-cal them in phase
2) concat them to SB data and self-cal them in phase
3) check flux offsets
4) if there are flux offsets, go back to 1), but before re-starting the process apply
    the corrections to the non-self caled ACA and SB data, and re-do steps 1) - 3).
    For this you should add additional code (essentially copy/paste the code from the first
    iteration) that repeats steps 1-3, but saves all output with different filenames. Remember
    to use the right filenames when you continue the script after step 6
5) Check flux offsets of LB EBs to a correct SB EB
6) concat LB data to ACA+SB and continue with script

"""

flux_ref_EB = 'SB_EB0'

#if you had to choose an LB EB, then iterate over data_params_SBLB constructed like this:
#data_params_SBLB = data_params_LB.copy()
#data_params_SBLB.update(data_params_SB)
#in that case, the call to estimate_flux_scale is just for exploring purposes by looking at the
#figures. in particular, the derived flux scalings are not used anywhere. this is because
#we need an SB EB to derive flux scalings, because only SB has overlapping baselines
#with both LB and ACA

for params in data_params.values():
    estimate_flux_scale(reference=prefix+f'_{flux_ref_EB}_initcont_shift.vis.npz',
                        comparison=prefix+'_'+params['name']+'_initcont_shift.vis.npz',
                        incl=incl, PA=PA,
                        plot_label=os.path.join(flux_comparison_folder,
                                                'flux_comparison_'+params['name']+f'_to_{flux_ref_EB}.png'))


#The ratio of the fluxes of J1615_LB_EB0_initcont_shift.vis.npz to
#J1615_SB_EB0_initcont_shift.vis.npz is 0.91395
#The scaling factor for gencal is 0.956 for your comparison measurement
#The error on the weighted mean ratio is 4.320e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_LB_EB1_initcont_shift.vis.npz to
#J1615_SB_EB0_initcont_shift.vis.npz is 0.99159
#The scaling factor for gencal is 0.996 for your comparison measurement
#The error on the weighted mean ratio is 3.884e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_LB_EB2_initcont_shift.vis.npz to
#J1615_SB_EB0_initcont_shift.vis.npz is 0.96757
#The scaling factor for gencal is 0.984 for your comparison measurement
#The error on the weighted mean ratio is 2.683e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_LB_EB3_initcont_shift.vis.npz to
#J1615_SB_EB0_initcont_shift.vis.npz is 0.94026
#The scaling factor for gencal is 0.970 for your comparison measurement
#The error on the weighted mean ratio is 3.305e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_SB_EB0_initcont_shift.vis.npz to
#J1615_SB_EB0_initcont_shift.vis.npz is 1.00000
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 1.618e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_SB_EB1_initcont_shift.vis.npz to
#J1615_SB_EB0_initcont_shift.vis.npz is 1.01266
#The scaling factor for gencal is 1.006 for your comparison measurement
#The error on the weighted mean ratio is 1.678e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_ACA_EB0_initcont_shift.vis.npz to
#J1615_SB_EB0_initcont_shift.vis.npz is 0.97145
#The scaling factor for gencal is 0.986 for your comparison measurement
#The error on the weighted mean ratio is 1.870e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_ACA_EB1_initcont_shift.vis.npz to
#J1615_SB_EB0_initcont_shift.vis.npz is 0.88084
#The scaling factor for gencal is 0.939 for your comparison measurement
#The error on the weighted mean ratio is 1.860e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_ACA_EB2_initcont_shift.vis.npz to
#J1615_SB_EB0_initcont_shift.vis.npz is 0.97001
#The scaling factor for gencal is 0.985 for your comparison measurement
#The error on the weighted mean ratio is 8.705e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#ACA EB0 and EB1 show heavy de-coherence, we do not rescale it until after self-cal of ACA+SB...
#LB EBs also show de-coherence, whereas SB EBs seem ok... so we may need to go all the way until the end
# with phase only self-cal and then decide what to do...


"""
Self-cal of ACA data only
"""
#for phase self-cal, we clean down to 6 sigma

ACA_selfcal_folder = get_figures_folderpath('7_selfcal_ACA_figures')
make_figures_folder(ACA_selfcal_folder)

""" Merge the SB executions back into a single MS """
ACA_cont_p0 = prefix+'_ACA_contp0'
os.system('rm -rf %s.ms*' % ACA_cont_p0)
concat(vis=[f'{prefix}_ACA_EB{i}_initcont_shift.ms' for i in range(number_of_EBs['ACA'])],
       concatvis=ACA_cont_p0+'.ms',dirtol='0.1arcsec',copypointing=False)

listobs(
    vis=ACA_cont_p0+'.ms',
    listfile=ACA_cont_p0+'.ms.txt',
    overwrite=True,
)

"""Define mask for ACA clean, using the new center J2000 04h39m17.80970s +22.21.02.9917"""
mask_ra = '16h15m20.22190s'
mask_dec = '-32.55.05.6123'
mask_semimajor_ACA = 9. #semimajor axis of mask in arcsec
mask_semiminor_ACA = 9. #semiminor axis of mask in arcsec
mask_ACA = f'ellipse[[{mask_ra},{mask_dec}], [{mask_semimajor_ACA:.3f}arcsec, {mask_semiminor_ACA:.3f}arcsec], {mask_pa:.1f}deg]'
# Cellsize: ~beam/6-7, synthesized beam: ~3.3-5'' (ACA)
ACA_cellsize =  '0.4arcsec'
# Image size: ~primary beam 1.22*lam/A = 32'' with A=7m
ACA_imsize = 100 # primary beam

noise_annulus_ACA = f"annulus[[{mask_ra}, {mask_dec}], ['10.arcsec', '18.arcsec']]"

""" Initial clean (down to 6 sigma)"""
tclean_wrapper(vis=ACA_cont_p0+'.ms', imagename = ACA_cont_p0, mask=mask_ACA, deconvolver='hogbom',
               threshold = '9mJy', savemodel = 'modelcolumn', imsize=ACA_imsize,
               cellsize=ACA_cellsize, robust=0.5, interactive=False, parallel=use_parallel)
estimate_SNR(ACA_cont_p0+'.image', disk_mask = mask_ACA, noise_mask = noise_annulus_ACA)
#J1615_ACA_contp0.image
#Beam 4.703 arcsec x 2.973 arcsec (89.75 deg)
#Flux inside disk mask: 371.85 mJy
#Peak intensity of source: 341.81 mJy/beam
#rms: 1.67e+00 mJy/beam
#Peak SNR: 204.12
rms_ACA = imstat(imagename = ACA_cont_p0+'.image', region = noise_annulus_ACA)['rms'][0]
generate_image_png(ACA_cont_p0+'.image',plot_sizes=image_png_plot_sizes['ACA'],
                   color_scale_limits=[-3*rms_ACA,10*rms_ACA],
                   save_folder=ACA_selfcal_folder)


""" Self-calibration parameters """

""" Look for references antennas from weblog, and pick the first that are listed, overlapping with all EBs """

#ACA uid___A002_Xf287d3_X1429f.ms CM02, CM03, CM05, CM08, CM10, CM12, CM09, CM11, CM01
#ACA uid___A002_Xf49cca_X1645a.ms CM10, CM03, CM02, CM12, CM05, CM06, CM07, CM01, CM09, CM11
#ACA uid___A002_Xf6a177_X270e.ms CM10, CM03, CM02, CM12, CM05, CM06, CM07, CM01, CM09, CM11

get_station_numbers(ACA_cont_p0+'.ms','CM02')
get_station_numbers(ACA_cont_p0+'.ms','CM10')
#Observation ID 0: CM02@J502
#Observation ID 1: CM02@J502
#Observation ID 2: CM02@J502
#Observation ID 0: CM10@J501
#Observation ID 1: CM10@J501
#Observation ID 2: CM10@J501

ACA_refant   = 'CM02@J502, CM10@J501'

ACA_contspws = '0~11'
ACA_spw_mapping = [0,0,0,0,4,4,4,4,8,8,8,8]

""" First round of phase-only self-cal """
# Use scan-length interval to align SPWs as much as possible
ACA_p1 = prefix+'_ACA.p1'
os.system('rm -rf '+ACA_p1)
gaincal(vis=ACA_cont_p0+'.ms', caltable=ACA_p1, gaintype='G', spw=ACA_contspws,
        refant=ACA_refant, combine='scan', calmode='p', solint='inf', minsnr=3., minblperant=3)


""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(ACA_p1,xaxis='time', yaxis='GainPhase')
""" Print calibration png file """
plotms(ACA_p1,xaxis='time', yaxis='GainPhase',overwrite=True,showgui=False,
       plotfile=os.path.join(ACA_selfcal_folder,prefix+'_ACA_gain_p1_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=ACA_cont_p0+'.ms', spw=ACA_contspws, gaintable=[ACA_p1],
         interp='linear', calwt=True, applymode='calonly')

""" Split off a corrected MS """
ACA_cont_p1 = prefix+'_ACA_contp1'
os.system('rm -rf %s.ms*' % ACA_cont_p1)
split(vis=ACA_cont_p0+'.ms', outputvis=ACA_cont_p1+'.ms', datacolumn='corrected')


""" Image the results; check the resulting map """
#again clean down to 6 sigma
tclean_wrapper(vis=ACA_cont_p1+'.ms', imagename = ACA_cont_p1, mask=mask_ACA, threshold = '10mJy', 
                deconvolver='hogbom', savemodel = 'modelcolumn', imsize=ACA_imsize,
                cellsize=ACA_cellsize, robust=0.5, interactive=False, parallel=use_parallel)
estimate_SNR(ACA_cont_p1+'.image', disk_mask = mask_ACA, noise_mask = noise_annulus_ACA)
generate_image_png(ACA_cont_p1+'.image',plot_sizes=image_png_plot_sizes['ACA'],
                   color_scale_limits=[-3*rms_ACA,10*rms_ACA],
                   save_folder=ACA_selfcal_folder)

#J1615_ACA_contp1.image
#Beam 4.631 arcsec x 2.966 arcsec (-89.86 deg)
#Flux inside disk mask: 367.09 mJy
#Peak intensity of source: 340.65 mJy/beam
#rms: 1.61e+00 mJy/beam
#Peak SNR: 211.28


""" Second round of phase-only self-cal (ACA only) """
ACA_p2 = prefix+'_ACA.p2'
os.system('rm -rf '+ACA_p2)
gaincal(vis=ACA_cont_p1+'.ms', caltable=ACA_p2, gaintype='T', spw=ACA_contspws,
        refant=ACA_refant, combine='spw', calmode='p', solint='30s', minsnr=3., minblperant=3)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(ACA_p2,xaxis='time', yaxis='GainPhase')
""" Print calibration png file """
plotms(ACA_p2,xaxis='time', yaxis='GainPhase',overwrite=True,showgui=False,
       plotfile=os.path.join(ACA_selfcal_folder,prefix+'_ACA_gain_p2_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=ACA_cont_p1+'.ms', spw=ACA_contspws, spwmap = ACA_spw_mapping, gaintable=[ACA_p2], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
ACA_cont_p2 = prefix+'_ACA_contp2'
os.system('rm -rf %s.ms*' % ACA_cont_p2)
split(vis=ACA_cont_p1+'.ms', outputvis=ACA_cont_p2+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=ACA_cont_p2+'.ms', imagename = ACA_cont_p2, mask=mask_ACA, threshold = '6mJy', 
                deconvolver='hogbom', savemodel = 'modelcolumn', imsize=ACA_imsize,
                cellsize=ACA_cellsize, robust=0.5, interactive=False, parallel=use_parallel)
estimate_SNR(ACA_cont_p2+'.image', disk_mask = mask_ACA, noise_mask = noise_annulus_ACA)
generate_image_png(ACA_cont_p2+'.image',plot_sizes=image_png_plot_sizes['ACA'],
                   color_scale_limits=[-3*rms_ACA,10*rms_ACA],
                   save_folder=ACA_selfcal_folder)

#J1615_ACA_contp2.image
#Beam 4.631 arcsec x 2.966 arcsec (-89.86 deg)
#Flux inside disk mask: 383.74 mJy
#Peak intensity of source: 356.26 mJy/beam
#rms: 8.31e-01 mJy/beam
#Peak SNR: 428.85

#Let's try cleaning deeper as a test 
tclean_wrapper(vis=ACA_cont_p2+'.ms', imagename = ACA_cont_p2, mask=mask_ACA, threshold = '1mJy', 
                deconvolver='hogbom', savemodel = 'modelcolumn', imsize=ACA_imsize,
                cellsize=ACA_cellsize, robust=0.5, interactive=False, parallel=use_parallel)
estimate_SNR(ACA_cont_p2+'.image', disk_mask = mask_ACA, noise_mask = noise_annulus_ACA)
generate_image_png(ACA_cont_p2+'.image',plot_sizes=image_png_plot_sizes['ACA'],
                   color_scale_limits=[-3*rms_ACA,10*rms_ACA],
                   save_folder=ACA_selfcal_folder)

#J1615_ACA_contp2.image
#Beam 4.631 arcsec x 2.966 arcsec (-89.86 deg)
#Flux inside disk mask: 400.14 mJy
#Peak intensity of source: 357.60 mJy/beam
#rms: 6.70e-01 mJy/beam
#Peak SNR: 533.47

non_self_caled_ACA_vis = ACA_cont_p0
self_caled_ACA_visibilities = {'p1':ACA_cont_p1,
                               'p2':ACA_cont_p2}

#be sure to check if the following is correct
ACA_EBs = ('EB0','EB1','EB2')
ACA_EB_spws = ('0,1,2,3','4,5,6,7','8,9,10,11')

for self_cal_step,self_caled_vis in self_caled_ACA_visibilities.items():
    for EB_key,spw in zip(ACA_EBs,ACA_EB_spws):
        nametemplate = f'{prefix}_ACA_{EB_key}_{self_cal_step}_compare_amp_vs_time'
        visibilities = [self_caled_vis+'.ms',non_self_caled_ACA_vis+'.ms']
        #we plot the whole uv range because sources are unresolved for ACA
        plot_amp_vs_time_comparison(
                nametemplate=nametemplate,visibilities=visibilities,spw=spw,
                uvrange=uv_ranges['ACA'],output_folder=ACA_selfcal_folder)


all_ACA_visibilities = self_caled_ACA_visibilities.copy()
all_ACA_visibilities['p0'] = ACA_cont_p0

for self_cal_step,vis_name in all_ACA_visibilities.items():
    #split out EBs
    vis_ms = vis_name+'.ms'
    nametemplate = vis_ms.replace('.ms','_EB')
    split_all_obs(msfile=vis_ms,nametemplate=nametemplate)
    exported_ms = []
    for i in range(number_of_EBs['ACA']):
        EB_vis = f'{nametemplate}{i}.ms'
        export_MS(EB_vis)
        exported_ms.append(EB_vis.replace('.ms','.vis.npz'))
    for i,exp_ms in enumerate(exported_ms):
        png_filename = f'flux_comparison_ACA_{self_cal_step}_{flux_ref_EB}_to_ACA_EB{i}.png'
        plot_label = os.path.join(ACA_selfcal_folder,png_filename)
        assert 'SB' in flux_ref_EB, 'comparison to ACA is only possible with SB (or ACA itself)'
        estimate_flux_scale(reference=prefix+f'_{flux_ref_EB}_initcont_shift.vis.npz',
                            comparison=exp_ms,incl=incl,
                            PA=PA,plot_label=plot_label)
    fluxscale = [1.,]*number_of_EBs['ACA']
    plot_label = os.path.join(ACA_selfcal_folder,
                              f'deprojected_vis_profiles_ACA_{self_cal_step}.png')
    plot_deprojected(filelist=exported_ms,fluxscale=fluxscale, PA=PA, incl=incl,
                     show_err=True,plot_label=plot_label)

#Saving observation 0 of J1615_ACA_contp1.ms to J1615_ACA_contp1_EB0.ms
#Saving observation 1 of J1615_ACA_contp1.ms to J1615_ACA_contp1_EB1.ms
#Saving observation 2 of J1615_ACA_contp1.ms to J1615_ACA_contp1_EB2.ms
#Measurement set exported to J1615_ACA_contp1_EB0.vis.npz
#Measurement set exported to J1615_ACA_contp1_EB1.vis.npz
#Measurement set exported to J1615_ACA_contp1_EB2.vis.npz

#The ratio of the fluxes of J1615_ACA_contp0_EB0.vis.npz to
#J1615_SB_EB0_initcont_shift.vis.npz is 0.97145
#The scaling factor for gencal is 0.986 for your comparison measurement
#The error on the weighted mean ratio is 1.870e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_ACA_contp0_EB1.vis.npz to
#J1615_SB_EB0_initcont_shift.vis.npz is 0.88084
#The scaling factor for gencal is 0.939 for your comparison measurement
#The error on the weighted mean ratio is 1.860e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_ACA_contp0_EB2.vis.npz to
#J1615_SB_EB0_initcont_shift.vis.npz is 0.97001
#The scaling factor for gencal is 0.985 for your comparison measurement
#The error on the weighted mean ratio is 8.705e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

# Decoherence does not look fixed. 

# we'll decide whether to rescale after ACA+SB self-cal

"""SELF-CAL ACA + SB data"""
#reminder: clean down to 6 sigma for phase self-cal

SB_selfcal_folder = get_figures_folderpath('8_selfcal_ACASB_figures')
make_figures_folder(SB_selfcal_folder)

""" Merge the ACA self-cal'ed ms with SB ms"""
SB_cont_p0 = prefix+'_ACASB_contp0'
os.system('rm -rf %s.ms*' % SB_cont_p0)

concat(vis=[ACA_cont_p2+'.ms']+[f'{prefix}_SB_EB{i}_initcont_shift.ms' for i
                                          in range(number_of_EBs['SB'])],
            concatvis=SB_cont_p0+'.ms', dirtol='0.1arcsec', copypointing=False)

listobs(
    vis=SB_cont_p0+'.ms',
    listfile=SB_cont_p0+'.ms.txt',
    overwrite=True,
)


"""Define new SB mask using new center"""
mask_pa = PA #position angle of mask in degrees
mask_semimajor = 2.7 #semimajor axis of mask in arcsec
mask_semiminor = mask_semimajor*np.cos(incl/180.*np.pi) #semiminor axis of mask in arcsec
mask_ra = '16h15m20.221900s'
mask_dec = '-32.55.05.61230'

SB_mask= f'ellipse[[{mask_ra},{mask_dec}], [{mask_semimajor:.3f}arcsec, {mask_semiminor:.3f}arcsec], {mask_pa:.1f}deg]'
# Cellsize: ~beam/6-7

SB_cellsize =  '0.040arcsec'
SB_imsize = 400 # primary beam
SB_scales = [0,8,15,30]

noise_annulus_SB = f"annulus[[{mask_ra}, {mask_dec}],['4.arcsec', '6.arcsec']]"

tclean_wrapper(vis=SB_cont_p0+'.ms', imagename = SB_cont_p0, mask=SB_mask, threshold = '0.75mJy', deconvolver='multiscale', scales=SB_scales, savemodel = 'modelcolumn', imsize=SB_imsize, cellsize=SB_cellsize, robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(SB_cont_p0+'.image', disk_mask = SB_mask, noise_mask = noise_annulus_SB)
#J1615_ACASB_contp0.image
#Beam 0.534 arcsec x 0.442 arcsec (-83.84 deg)
#Flux inside disk mask: 386.69 mJy
#Peak intensity of source: 102.27 mJy/beam
#rms: 1.09e-01 mJy/beam
#Peak SNR: 940.64

rms_SB = imstat(imagename = SB_cont_p0+'.image', region = noise_annulus_SB)['rms'][0]
generate_image_png(SB_cont_p0+'.image',plot_sizes=image_png_plot_sizes['SB'],
                   color_scale_limits=[-3*rms_SB,10*rms_SB],save_folder=SB_selfcal_folder)

""" Look for references antennas from weblog, and pick the first that are listed, overlapping with all EBs """
""" Since we are combined ACA EBs to SB EBs, ref antennas for both ACA and SB are needed """

#SB uid___A002_Xf7ad58_X1f60.ms DA63, DA52, DA57, DV08, DV14, DV18, DV16, DV17, DV13, DA50, DV25, DV23, DV19, DV06, DV07, DA47, DV10, DA55, DV15, DA42, DV21, DA44, DV02, DV03, DA58, DV12, PM03, DA61, DA46, DA62, DA65, DV05, PM01, DA48, DA54, DV20, DA53, DA56, DA43, PM04, DA60, DA51, DA41, DV22, DA59, DV11
#SB uid___A002_Xf7ad58_X6871.ms DA63, DA52, DA57, DV08, DV14, DV18, DV17, DV16, DV13, DA50, DA55, DV25, DV23, DV07, DV19, DV06, DV10, DA47, DA42, DA44, DV15, DV03, DA58, DV21, DV02, DV12, PM03, DV01, DA61, DA46, DA62, DA65, DV05, PM01, DA48, DV20, DA54, DA53, DA56, DA43, PM04, DA51, DA41, DA60, DA59, DV11, DV22

""" Get station numbers """
get_station_numbers(SB_cont_p0+'.ms','DA63')
get_station_numbers(SB_cont_p0+'.ms','DA52')

#Observation ID 3: DA63@A035
#Observation ID 4: DA63@A035
#Observation ID 3: DA52@A002
#Observation ID 4: DA52@A002

#add spw for ACA (12) + SB (8) & refant for both ACA and SB
SB_contspws = '0~19'
SB_refant   = 'DA63@A035, DA52@A002, CM02@J502, CM10@J501'

SB_spw_mapping = [0,0,0,0,4,4,4,4,8,8,8,8, 12, 12, 12, 12, 16, 16, 16, 16]

SB_p1 = prefix+'_ACASB.p1'
os.system('rm -rf '+SB_p1)
gaincal(vis=SB_cont_p0+'.ms', caltable=SB_p1, gaintype='G', spw=SB_contspws,
        refant=SB_refant, combine='scan,spw', calmode='p', solint='inf', minsnr=3., minblperant=4)
# I combine spws

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(SB_p1,xaxis='time', yaxis='GainPhase',iteraxis='spw')
#manual flag a few solutions

""" Print calibration png file """
plotms(SB_p1,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(SB_selfcal_folder,prefix+'_SB_gain_p1_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=SB_cont_p0+'.ms', spw=SB_contspws, spwmap = SB_spw_mapping, gaintable=[SB_p1], interp='linearPD', calwt=True, applymode='calonly')

SB_cont_p1 = prefix+'_ACASB_contp1'
os.system('rm -rf %s.ms*' % SB_cont_p1)
split(vis=SB_cont_p0+'.ms', outputvis=SB_cont_p1+'.ms', datacolumn='corrected')

tclean_wrapper(vis=SB_cont_p1+'.ms', imagename = SB_cont_p1, mask=SB_mask, threshold = '0.65mJy', deconvolver='multiscale', scales=SB_scales, savemodel = 'modelcolumn', imsize=SB_imsize, cellsize=SB_cellsize, robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(SB_cont_p1+'.image', disk_mask = SB_mask, noise_mask = noise_annulus_SB)
generate_image_png(SB_cont_p1+'.image',plot_sizes=image_png_plot_sizes['SB'],
                   color_scale_limits=[-3*rms_SB,10*rms_SB],save_folder=SB_selfcal_folder)

#J1615_ACASB_contp1.image
#Beam 0.534 arcsec x 0.442 arcsec (-83.84 deg)
#Flux inside disk mask: 387.05 mJy
#Peak intensity of source: 102.29 mJy/beam
#rms: 9.93e-02 mJy/beam
#Peak SNR: 1029.63


SB_p2 = prefix+'_ACASB.p2'
os.system('rm -rf '+SB_p2)
gaincal(vis=SB_cont_p1+'.ms', caltable=SB_p2, gaintype='T', spw=SB_contspws,
        refant=SB_refant, combine='scan, spw', calmode='p', solint='360s', minsnr=3., minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(SB_p2,xaxis='time', yaxis='GainPhase',iteraxis='spw')

""" Print calibration png file """
plotms(SB_p2,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(SB_selfcal_folder,prefix+'_SB_gain_p2_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=SB_cont_p1+'.ms', spw=SB_contspws, spwmap = SB_spw_mapping, gaintable=[SB_p2], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
SB_cont_p2 = prefix+'_ACASB_contp2'
os.system('rm -rf %s.ms*' % SB_cont_p2)
split(vis=SB_cont_p1+'.ms', outputvis=SB_cont_p2+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=SB_cont_p2+'.ms', imagename = SB_cont_p2, mask=SB_mask, threshold = '1mJy', deconvolver='multiscale', scales=SB_scales, savemodel = 'modelcolumn', imsize=SB_imsize, cellsize=SB_cellsize, robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(SB_cont_p2+'.image', disk_mask = SB_mask, noise_mask = noise_annulus_SB)
generate_image_png(SB_cont_p2+'.image',plot_sizes=image_png_plot_sizes['SB'],
                   color_scale_limits=[-3*rms_SB,10*rms_SB],save_folder=SB_selfcal_folder)

#J1615_ACASB_contp2.image
#Beam 0.534 arcsec x 0.442 arcsec (-83.84 deg)
#Flux inside disk mask: 386.47 mJy
#Peak intensity of source: 102.71 mJy/beam
#rms: 9.79e-02 mJy/beam
#Peak SNR: 1049.42


#Let's clean a bit deeper
tclean_wrapper(vis=SB_cont_p2+'.ms', imagename = SB_cont_p2, mask=SB_mask, threshold = '0.6mJy', deconvolver='multiscale', scales=SB_scales, savemodel = 'modelcolumn', imsize=SB_imsize, cellsize=SB_cellsize, robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(SB_cont_p2+'.image', disk_mask = SB_mask, noise_mask = noise_annulus_SB)
generate_image_png(SB_cont_p2+'.image',plot_sizes=image_png_plot_sizes['SB'],
                   color_scale_limits=[-3*rms_SB,10*rms_SB],save_folder=SB_selfcal_folder)

#J1615_ACASB_contp2.image
#Beam 0.534 arcsec x 0.442 arcsec (-83.84 deg)
#Flux inside disk mask: 387.59 mJy
#Peak intensity of source: 102.66 mJy/beam
#rms: 7.89e-02 mJy/beam
#Peak SNR: 1301.36

SB_p3 = prefix+'_ACASB.p3'
os.system('rm -rf '+SB_p3)
gaincal(vis=SB_cont_p2+'.ms', caltable=SB_p3, gaintype='T', spw=SB_contspws,
        refant=SB_refant, combine='spw', calmode='p', solint='120s', minsnr=3., minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(SB_p3,xaxis='time', yaxis='GainPhase',iteraxis='spw')


""" Print calibration png file """
plotms(SB_p3,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(SB_selfcal_folder,prefix+'_SB_gain_p3_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=SB_cont_p2+'.ms', spw=SB_contspws, spwmap = SB_spw_mapping, gaintable=[SB_p3], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
SB_cont_p3 = prefix+'_ACASB_contp3'
os.system('rm -rf %s.ms*' % SB_cont_p3)
split(vis=SB_cont_p2+'.ms', outputvis=SB_cont_p3+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=SB_cont_p3+'.ms', imagename = SB_cont_p3, mask=SB_mask, threshold = '0.5mJy', deconvolver='multiscale', scales=SB_scales, savemodel = 'modelcolumn', imsize=SB_imsize, cellsize=SB_cellsize, robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(SB_cont_p3+'.image', disk_mask = SB_mask, noise_mask = noise_annulus_SB)
generate_image_png(SB_cont_p3+'.image',plot_sizes=image_png_plot_sizes['SB'],
                   color_scale_limits=[-3*rms_SB,10*rms_SB],save_folder=SB_selfcal_folder)

#J1615_ACASB_contp3.image
#Beam 0.534 arcsec x 0.442 arcsec (-83.84 deg)
#Flux inside disk mask: 387.98 mJy
#Peak intensity of source: 102.84 mJy/beam
#rms: 7.23e-02 mJy/beam
#Peak SNR: 1422.50

SB_p4 = prefix+'_ACASB.p4'
os.system('rm -rf '+SB_p4)
gaincal(vis=SB_cont_p3+'.ms', caltable=SB_p4, gaintype='T', spw=SB_contspws,
        refant=SB_refant, combine='spw', calmode='p', solint='60s', minsnr=3., minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(SB_p4,xaxis='time', yaxis='GainPhase',iteraxis='spw')

""" Print calibration png file """
plotms(SB_p4,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(SB_selfcal_folder,prefix+'_SB_gain_p4_phase_vs_time.png'))

applycal(vis=SB_cont_p3+'.ms', spw=SB_contspws, spwmap = SB_spw_mapping, gaintable=[SB_p4], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
SB_cont_p4 = prefix+'_ACASB_contp4'
os.system('rm -rf %s.ms*' % SB_cont_p4)
split(vis=SB_cont_p3+'.ms', outputvis=SB_cont_p4+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=SB_cont_p4+'.ms', imagename = SB_cont_p4, mask=SB_mask, threshold = '0.5mJy', deconvolver='multiscale', scales=SB_scales, savemodel = 'modelcolumn', imsize=SB_imsize, cellsize=SB_cellsize, robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(SB_cont_p4+'.image', disk_mask = SB_mask, noise_mask = noise_annulus_SB)
generate_image_png(SB_cont_p4+'.image',plot_sizes=image_png_plot_sizes['SB'],
                   color_scale_limits=[-3*rms_SB,10*rms_SB],save_folder=SB_selfcal_folder)

#J1615_ACASB_contp4.image
#Beam 0.534 arcsec x 0.442 arcsec (-83.84 deg)
#Flux inside disk mask: 388.06 mJy
#Peak intensity of source: 102.95 mJy/beam
#rms: 7.04e-02 mJy/beam
#Peak SNR: 1461.84


SB_p5 = prefix+'_ACASB.p5'
os.system('rm -rf '+SB_p5)
gaincal(vis=SB_cont_p4+'.ms', caltable=SB_p5, gaintype='T', spw=SB_contspws,
        refant=SB_refant, combine='spw', calmode='p', solint='30s', minsnr=3., minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(SB_p5,xaxis='time', yaxis='GainPhase',iteraxis='spw')


""" Print calibration png file """
plotms(SB_p5,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(SB_selfcal_folder,prefix+'_SB_gain_p5_phase_vs_time.png'))

applycal(vis=SB_cont_p4+'.ms', spw=SB_contspws, spwmap = SB_spw_mapping, gaintable=[SB_p5], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
SB_cont_p5 = prefix+'_ACASB_contp5'
os.system('rm -rf %s.ms*' % SB_cont_p5)
split(vis=SB_cont_p4+'.ms', outputvis=SB_cont_p5+'.ms', datacolumn='corrected')


""" Image the results; check the resulting map """
tclean_wrapper(vis=SB_cont_p5+'.ms', imagename = SB_cont_p5, mask=SB_mask, threshold = '0.45mJy', deconvolver='multiscale', scales=SB_scales, savemodel = 'modelcolumn', imsize=SB_imsize, cellsize=SB_cellsize, robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(SB_cont_p5+'.image', disk_mask = SB_mask, noise_mask = noise_annulus_SB)
generate_image_png(SB_cont_p5+'.image',plot_sizes=image_png_plot_sizes['SB'],
                   color_scale_limits=[-3*rms_SB,10*rms_SB],save_folder=SB_selfcal_folder)


#J1615_ACASB_contp5.image
#Beam 0.534 arcsec x 0.442 arcsec (-83.84 deg)
#Flux inside disk mask: 388.18 mJy
#Peak intensity of source: 103.09 mJy/beam
#rms: 6.87e-02 mJy/beam
#Peak SNR: 1500.65

SB_p6 = prefix+'_ACASB.p6'
os.system('rm -rf '+SB_p6)
gaincal(vis=SB_cont_p5+'.ms', caltable=SB_p6, gaintype='T', spw=SB_contspws,
        refant=SB_refant, combine='spw', calmode='p', solint='20s', minsnr=3., minblperant=4)


""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(SB_p6,xaxis='time', yaxis='GainPhase',iteraxis='spw')

""" Print calibration png file """
plotms(SB_p6,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(SB_selfcal_folder,prefix+'_SB_gain_p6_phase_vs_time.png'))

applycal(vis=SB_cont_p5+'.ms', spw=SB_contspws, spwmap = SB_spw_mapping, gaintable=[SB_p6], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
SB_cont_p6 = prefix+'_ACASB_contp6'
os.system('rm -rf %s.ms*' % SB_cont_p6)
split(vis=SB_cont_p5+'.ms', outputvis=SB_cont_p6+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=SB_cont_p6+'.ms', imagename = SB_cont_p6, mask=SB_mask, threshold = '0.45mJy', deconvolver='multiscale', scales=SB_scales, savemodel = 'modelcolumn', imsize=SB_imsize, cellsize=SB_cellsize, robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(SB_cont_p6+'.image', disk_mask = SB_mask, noise_mask = noise_annulus_SB)
generate_image_png(SB_cont_p6+'.image',plot_sizes=image_png_plot_sizes['SB'],
                   color_scale_limits=[-3*rms_SB,10*rms_SB],save_folder=SB_selfcal_folder)

#J1615_ACASB_contp6.image
#Beam 0.534 arcsec x 0.442 arcsec (-83.84 deg)
#Flux inside disk mask: 388.37 mJy
#Peak intensity of source: 103.16 mJy/beam
#rms: 6.85e-02 mJy/beam
#Peak SNR: 1506.79

#no particular improvement - we still keep the 20s solutions

#plot amp vs time for a narrow uv range
non_self_caled_SB_vis = SB_cont_p0
self_caled_SB_visibilities = {'p1':SB_cont_p1,
                              'p2':SB_cont_p2,
                              'p3':SB_cont_p3,
                              'p4':SB_cont_p4,
                              'p5':SB_cont_p5,
                              'p6':SB_cont_p6}

SB_EBs = ('EB0','EB1')
SB_EB_spws = ('12,13,14,15','16,17,18,19') #fill in spws for each EB


for self_cal_step,self_caled_vis in self_caled_SB_visibilities.items():
    for EB_key,spw in zip(SB_EBs,SB_EB_spws):
        nametemplate = f'{prefix}_SB_{EB_key}_{self_cal_step}_compare_amp_vs_time'
        visibilities = [self_caled_vis+'.ms',non_self_caled_SB_vis+'.ms']
        plot_amp_vs_time_comparison(
                nametemplate=nametemplate,visibilities=visibilities,spw=spw,
                uvrange=uv_ranges['SB'],output_folder=SB_selfcal_folder)


all_SB_visibilities = self_caled_SB_visibilities.copy()
all_SB_visibilities['p0'] = SB_cont_p0

"""
if SB suffers from decoherence, then take an LB EB as flux reference; modify the code
below accordingly

If you haven't re-scaled the fluxes of LB EBs because all SB EBs had high decoherence,
check flux offsets of LB EBs here and correct them, if needed

"""

for self_cal_step,vis_name in all_SB_visibilities.items():
    #split out SB EBs
    vis_ms = vis_name+'.ms'
    nametemplate = vis_ms.replace('.ms','_EB')
    split_all_obs(msfile=vis_ms,nametemplate=nametemplate)
    exported_ms = []
    #we only compare SB to LB, not ACA to LB
    for i in range(number_of_EBs['ACA'],number_of_EBs['SB']+number_of_EBs['ACA']):
        EB_vis = f'{nametemplate}{i}.ms'
        export_MS(EB_vis) #export MS contents into Numpy save files
        exported_ms.append(EB_vis.replace('.ms','.vis.npz'))
    for i,exp_ms in zip(range(number_of_EBs['ACA'],number_of_EBs['SB']+number_of_EBs['ACA']),exported_ms):
        png_filename = f'flux_comparison_ACASB_EB{i}_{self_cal_step}_to_{flux_ref_EB}.png'
        plot_label = os.path.join(SB_selfcal_folder,png_filename)
        estimate_flux_scale(reference=f'{prefix}_{flux_ref_EB}_initcont_shift.vis.npz',
                            comparison=exp_ms,incl=incl,PA=PA,plot_label=plot_label)
    fluxscale = [1.,]*number_of_EBs['SB']
    plot_label = os.path.join(SB_selfcal_folder,
                              f'deprojected_vis_profiles_SB_{self_cal_step}.png')
    plot_deprojected(filelist=exported_ms,fluxscale=fluxscale, PA=PA, incl=incl,
                     show_err=True,plot_label=plot_label)



#The ratio of the fluxes of J1615_ACASB_contp0_EB3.vis.npz to
#J1615_SB_EB0_initcont_shift.vis.npz is 1.00000
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 1.618e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_ACASB_contp0_EB4.vis.npz to
#J1615_SB_EB0_initcont_shift.vis.npz is 1.01266
#The scaling factor for gencal is 1.006 for your comparison measurement
#The error on the weighted mean ratio is 1.678e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#some decoherence remains but it's much better

#Let's look at ACA EBs as well:
self_caled_SB_visibilities = {}
self_caled_SB_visibilities = {'p6':SB_cont_p6}
all_SB_visibilities = self_caled_SB_visibilities.copy()

for self_cal_step,vis_name in all_SB_visibilities.items():
    #split out SB EBs
    vis_ms = vis_name+'.ms'
    nametemplate = vis_ms.replace('.ms','_EB')
    split_all_obs(msfile=vis_ms,nametemplate=nametemplate)
    #we only compare SB to LB, not ACA to LB
    for i in range(number_of_EBs['SB']+number_of_EBs['ACA']):
        EB_vis = f'{nametemplate}{i}.ms'
        export_MS(EB_vis) #export MS contents into Numpy save files



list_npz_files = []

list_npz_files = [f'{prefix}_ACASB_contp6_EB0.vis.npz',
                  f'{prefix}_ACASB_contp6_EB1.vis.npz',
                  f'{prefix}_ACASB_contp6_EB2.vis.npz',
                  f'{prefix}_ACASB_contp6_EB3.vis.npz',
                  f'{prefix}_ACASB_contp6_EB4.vis.npz',
                  f'{prefix}_LB_EB0_initcont_shift.vis.npz',
                  f'{prefix}_LB_EB1_initcont_shift.vis.npz',
                  f'{prefix}_LB_EB2_initcont_shift.vis.npz',
                  f'{prefix}_LB_EB3_initcont_shift.vis.npz']

plot_label = os.path.join(SB_selfcal_folder,
                          f'deprojected_vis_profiles_ACASB_p6_and_LB.png')

plot_deprojected(filelist=list_npz_files,
                 fluxscale=[1.]*(number_of_EBs['LB']+number_of_EBs['SB']+number_of_EBs['ACA']),PA=PA,incl=incl,show_err=True,
                 plot_label=plot_label)
# Deprojected flux is much better than before self-cal

# As reference here we use the self-cal'ed SB EB0, which is now ACASB EB3
for i in np.arange(number_of_EBs['SB']+number_of_EBs['ACA']):
    estimate_flux_scale(reference=f'{prefix}_ACASB_contp6_EB3.vis.npz',
                            comparison=f'{prefix}_ACASB_contp6_EB'+str(i)+'.vis.npz',incl=incl,PA=PA,
                            plot_label=os.path.join(SB_selfcal_folder,f'{prefix}_ACASB_contp6_EB'+str(i)+'_to_ACASB_contp6_EB3_comparison.png'))

#The ratio of the fluxes of J1615_ACASB_contp6_EB0.vis.npz to
#J1615_ACASB_contp6_EB3.vis.npz is 1.07594
#The scaling factor for gencal is 1.037 for your comparison measurement
#The error on the weighted mean ratio is 1.868e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor


#The ratio of the fluxes of J1615_ACASB_contp6_EB1.vis.npz to
#J1615_ACASB_contp6_EB3.vis.npz is 0.99388
#The scaling factor for gencal is 0.997 for your comparison measurement
#The error on the weighted mean ratio is 1.859e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_ACASB_contp6_EB2.vis.npz to
#J1615_ACASB_contp6_EB3.vis.npz is 0.98151
#The scaling factor for gencal is 0.991 for your comparison measurement
#The error on the weighted mean ratio is 8.692e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_ACASB_contp6_EB3.vis.npz to
#J1615_ACASB_contp6_EB3.vis.npz is 1.00000
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 1.610e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_ACASB_contp6_EB4.vis.npz to
#J1615_ACASB_contp6_EB3.vis.npz is 1.01501
#The scaling factor for gencal is 1.007 for your comparison measurement
#The error on the weighted mean ratio is 1.671e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#De-coherence of ACA data has SIGNIFICANTLY improved
# It's very likely that we will have to rescale down ACA EB0. But since LB EBs have strong de-coherence,
# we do not rescale fluxes now, we go all the way until the end of phase self-cal, and then
# decide on flux-rescaling there

for i in np.arange(number_of_EBs['LB']):
    estimate_flux_scale(reference=f'{prefix}_ACASB_contp6_EB3.vis.npz',
                            comparison=f'{prefix}_LB_EB'+str(i)+'_initcont_shift.vis.npz',incl=incl,PA=PA,
                            plot_label=os.path.join(SB_selfcal_folder,f'{prefix}_LB_init_EB'+str(i)+'_to_ACASB_contp6_EB3_comparison.png'))
#The ratio of the fluxes of J1615_LB_EB0_initcont_shift.vis.npz to
#J1615_ACASB_contp6_EB3.vis.npz is 0.90759
#The scaling factor for gencal is 0.953 for your comparison measurement
#The error on the weighted mean ratio is 4.286e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_LB_EB1_initcont_shift.vis.npz to
#J1615_ACASB_contp6_EB3.vis.npz is 0.98477
#The scaling factor for gencal is 0.992 for your comparison measurement
#The error on the weighted mean ratio is 3.854e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_LB_EB2_initcont_shift.vis.npz to
#J1615_ACASB_contp6_EB3.vis.npz is 0.96171
#The scaling factor for gencal is 0.981 for your comparison measurement
#The error on the weighted mean ratio is 2.663e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_LB_EB3_initcont_shift.vis.npz to
#J1615_ACASB_contp6_EB3.vis.npz is 0.93444
#The scaling factor for gencal is 0.967 for your comparison measurement
#The error on the weighted mean ratio is 3.282e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#De-coherence of LB data is pretty bad. We continue with phase self-cal,
# and assess things at the end of phase only self-cal


"""SELF-CAL COMBINED DATA"""
LB_selfcal_folder = get_figures_folderpath('9_selfcal_ACASBLB_figures')
make_figures_folder(LB_selfcal_folder)


""" Merge the SB self-cal'ed ms with LB ms"""
LB_cont_p0 = prefix+'_ACASBLB_contp0'
os.system('rm -rf %s.ms*' % LB_cont_p0)

concat(vis=[SB_cont_p6+'.ms']+[f'{prefix}_LB_EB{i}_initcont_shift.ms' for i in
                               range(number_of_EBs['LB'])],
            concatvis=LB_cont_p0+'.ms', dirtol='0.1arcsec', copypointing=False)

listobs(
    vis=LB_cont_p0+'.ms',
    listfile=LB_cont_p0+'.ms.txt',
    overwrite=True,
)

mask_pa = PA #position angle of mask in degrees
mask_semimajor = 2.7 #semimajor axis of mask in arcsec
mask_semiminor = mask_semimajor*np.cos(incl/180.*np.pi) #semiminor axis of mask in arcsec
mask_ra = '16h15m20.221900s'
mask_dec = '-32.55.05.61230'

LB_mask = f'ellipse[[{mask_ra},{mask_dec}], [{mask_semimajor:.3f}arcsec, {mask_semiminor:.3f}arcsec], {mask_pa:.1f}deg]'
noise_annulus_LB = f"annulus[[{mask_ra}, {mask_dec}],['4.arcsec', '6.arcsec']]"


LB_cellsize =  '0.015arcsec'
LB_imsize = 1200 # primary beam
LB_scales=[0,10,20,50,120]

""" clean down to ~6 sigma"""
tclean_wrapper(vis=LB_cont_p0+'.ms', imagename = LB_cont_p0, mask=LB_mask, threshold = '0.15mJy', deconvolver='multiscale', scales=LB_scales, savemodel = 'modelcolumn', imsize=LB_imsize, cellsize=LB_cellsize, robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(LB_cont_p0+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
rms_LB = imstat(imagename = LB_cont_p0+'.image', region = noise_annulus_LB)['rms'][0]
generate_image_png(LB_cont_p0+'.image',plot_sizes=image_png_plot_sizes['LB'],
                   color_scale_limits=[-3*rms_LB,10*rms_LB],save_folder=LB_selfcal_folder)
#J1615_ACASBLB_contp0.image
#Beam 0.181 arcsec x 0.156 arcsec (-87.30 deg)
#Flux inside disk mask: 388.20 mJy
#Peak intensity of source: 17.40 mJy/beam
#rms: 3.15e-02 mJy/beam
#Peak SNR: 553.06

""" Self-calibration parameters """

""" Look for references antennas from weblog, and pick the first that are listed, overlapping with all EBs """
""" Since we are combined LB EBs to SB+ACA EBs, ref antennas for LB, SB and ACA are needed """
#Ref antennas for SB and ACA were: 'DA63@A035, DA52@A002, CM02@J502, CM10@J501'
#For LB, no weblog now, so we pick antennas at the center of the array:
plotants('J1615_LB_EB0_initcont.ms')
plotants('J1615_LB_EB1_initcont.ms')
plotants('J1615_LB_EB2_initcont.ms')
plotants('J1615_LB_EB3_initcont.ms')
# DA61 and  seem ok for all EBs
get_station_numbers(LB_cont_p0+'.ms','DA63')
get_station_numbers(LB_cont_p0+'.ms','DA52')
get_station_numbers(LB_cont_p0+'.ms','DA61')
get_station_numbers(LB_cont_p0+'.ms','DA55')
#Observation ID 3: DA63@A035
#Observation ID 4: DA63@A035
#Observation ID 5: DA63@A116
#Observation ID 6: DA63@A116
#Observation ID 7: DA63@A023
#Observation ID 8: DA63@A023
#Observation ID 3: DA52@A002
#Observation ID 4: DA52@A002
#Observation ID 3: DA61@A016
#Observation ID 4: DA61@A016
#Observation ID 5: DA61@A120
#Observation ID 6: DA61@A120
#Observation ID 7: DA61@A035
#Observation ID 3: DA55@A043
#Observation ID 4: DA55@A043
#Observation ID 5: DA55@A043
#Observation ID 6: DA55@A043
#Observation ID 7: DA55@A043
#Observation ID 8: DA55@A043


LB_refant   = 'DA63@A035, DA52@A002, DA61@A120, DA61@A120, DA55@A043, CM02@J502, CM10@J501'

LB_contspws = '0~179'


LB_spw_mapping_combine_scans = [0,0,0,0,
                                4,4,4,4,
                                8,8,8,8,
                                12,12,12,12,
                                16,16,16,16,
                                20,20,20,20,
                                20,20,20,20,
                                20,20,20,20,
                                20,20,20,20,
                                20,20,20,20,
                                20,20,20,20,
                                20,20,20,20,
                                20,20,20,20,
                                20,20,20,20,
                                20,20,20,20,
                                20,20,20,20,
                                20,20,20,20,
                                20,20,20,20,
                                20,20,20,20,
                                20,20,20,20,
                                20,20,20,20,
                                20,20,20,20,
                                20,20,20,20,
                                20,20,20,20,
                                20,20,20,20,
                                100,100,100,100,
                                100,100,100,100,
                                100,100,100,100,
                                100,100,100,100,
                                100,100,100,100,
                                100,100,100,100,
                                100,100,100,100,
                                100,100,100,100,
                                100,100,100,100,
                                100,100,100,100,
                                100,100,100,100,
                                100,100,100,100,
                                100,100,100,100,
                                100,100,100,100,
                                100,100,100,100,
                                100,100,100,100,
                                100,100,100,100,
                                100,100,100,100,
                                172,172,172,172,
                                176,176,176,176]


LB_spw_mapping_no_combine_scans = [0,0,0,0,
                                   4,4,4,4,
                                   8,8,8,8,
                                   12,12,12,12,
                                   16,16,16,16,
                                   20,20,20,20,
                                   24,24,24,24,
                                   28,28,28,28,
                                   32,32,32,32,
                                   36,36,36,36,
                                   40,40,40,40,
                                   44,44,44,44,
                                   48,48,48,48,
                                   52,52,52,52,
                                   56,56,56,56,
                                   60,60,60,60,
                                   64,64,64,64,
                                   68,68,68,68,
                                   72,72,72,72,
                                   76,76,76,76,
                                   80,80,80,80,
                                   84,84,84,84,
                                   88,88,88,88,
                                   92,92,92,92,
                                   96,96,96,96,
                                   100,100,100,100,
                                   104,104,104,104,
                                   108,108,108,108,
                                   112,112,112,112,
                                   116,116,116,116,
                                   120,120,120,120,
                                   124,124,124,124,
                                   128,128,128,128,
                                   132,132,132,132,
                                   136,136,136,136,
                                   140,140,140,140,
                                   144,144,144,144,
                                   148,148,148,148,
                                   152,152,152,152,
                                   156,156,156,156,
                                   160,160,160,160,
                                   164,164,164,164,
                                   168,168,168,168,
                                   172,172,172,172,
                                   176,176,176,176]



LB_p1 = prefix+'_ACASBLB.p1'
os.system('rm -rf '+LB_p1)
#try gaintype='G', and if there are many flagged solutions, change it to 'T'
gaincal(vis=LB_cont_p0+'.ms', caltable=LB_p1, gaintype='G', spw=LB_contspws,
        refant=LB_refant, combine='scan,spw', calmode='p', solint='inf', minsnr=2.,
        minblperant=4)
#2 of 84 solutions flagged due to SNR < 2 in spw=20 at 2022/07/25/23:57:28.3

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(LB_p1,xaxis='time', yaxis='GainPhase',iteraxis='spw')

""" Print calibration png file """
plotms(LB_p1,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_selfcal_folder,prefix+'_LB_gain_p1_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=LB_cont_p0+'.ms', spw=LB_contspws, spwmap = LB_spw_mapping_combine_scans, gaintable=[LB_p1], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
LB_cont_p1 = prefix+'_ACASBLB_contp1'
os.system('rm -rf %s.ms*' % LB_cont_p1)
split(vis=LB_cont_p0+'.ms', outputvis=LB_cont_p1+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=LB_cont_p1+'.ms', imagename = LB_cont_p1, mask=LB_mask, threshold = '0.15mJy', deconvolver='multiscale', scales=LB_scales, savemodel = 'modelcolumn', imsize=LB_imsize, cellsize=LB_cellsize, robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(LB_cont_p1+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
generate_image_png(LB_cont_p1+'.image',plot_sizes=image_png_plot_sizes['LB'],
                   color_scale_limits=[-3*rms_LB,10*rms_LB],save_folder=LB_selfcal_folder)

#J1615_ACASBLB_contp1.image
#Beam 0.181 arcsec x 0.156 arcsec (-87.30 deg)
#Flux inside disk mask: 388.56 mJy
#Peak intensity of source: 17.36 mJy/beam
#rms: 3.04e-02 mJy/beam
#Peak SNR: 571.13


#when not combining scans use in spwmap=LB_spw_mapping_no_combine_scans

""" Second round of phase-only self-cal (LB only) """
LB_p2 = prefix+'_ACASBLB.p2'
os.system('rm -rf '+LB_p2)
gaincal(vis=LB_cont_p1+'.ms', caltable=LB_p2, gaintype='T', spw=LB_contspws,
        refant=LB_refant, combine='spw', calmode='p', solint='180s', minsnr=2., minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(LB_p2,xaxis='time', yaxis='GainPhase',iteraxis='spw')

""" Print calibration png file """
plotms(LB_p2,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_selfcal_folder,prefix+'_LB_gain_p2_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=LB_cont_p1+'.ms', spw=LB_contspws, spwmap = LB_spw_mapping_no_combine_scans, gaintable=[LB_p2], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
LB_cont_p2 = prefix+'_ACASBLB_contp2'
os.system('rm -rf %s.ms*' % LB_cont_p2)
split(vis=LB_cont_p1+'.ms', outputvis=LB_cont_p2+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=LB_cont_p2+'.ms', imagename = LB_cont_p2, mask=LB_mask, threshold = '0.15mJy', deconvolver='multiscale', scales=LB_scales, savemodel = 'modelcolumn', imsize=LB_imsize, cellsize=LB_cellsize, robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(LB_cont_p2+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
generate_image_png(LB_cont_p2+'.image',plot_sizes=image_png_plot_sizes['LB'],
                   color_scale_limits=[-3*rms_LB,10*rms_LB],save_folder=LB_selfcal_folder)

#J1615_ACASBLB_contp2.image
#Beam 0.181 arcsec x 0.156 arcsec (-87.30 deg)
#Flux inside disk mask: 388.82 mJy
#Peak intensity of source: 17.58 mJy/beam
#rms: 2.57e-02 mJy/beam
#Peak SNR: 684.71


""" Third round of phase-only self-cal (LB only) """

LB_p3 = prefix+'_ACASBLB.p3'
os.system('rm -rf '+LB_p3)
gaincal(vis=LB_cont_p2+'.ms', caltable=LB_p3, gaintype='T', spw=LB_contspws,
        refant=LB_refant, combine='spw', calmode='p', solint='120s', minsnr=2., minblperant=4)
#Flagging up to 17 antennas in some time intervals for LB EBs, in particular LB EB0

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(LB_p3,xaxis='time', yaxis='GainPhase',iteraxis='spw')

""" Print calibration png file """
plotms(LB_p3,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_selfcal_folder,prefix+'_LB_gain_p3_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=LB_cont_p2+'.ms', spw=LB_contspws, spwmap = LB_spw_mapping_no_combine_scans, gaintable=[LB_p3], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
LB_cont_p3 = prefix+'_ACASBLB_contp3'
os.system('rm -rf %s.ms*' % LB_cont_p3)
split(vis=LB_cont_p2+'.ms', outputvis=LB_cont_p3+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=LB_cont_p3+'.ms', imagename = LB_cont_p3, mask=LB_mask, threshold = '0.15mJy', deconvolver='multiscale', scales=LB_scales, savemodel = 'modelcolumn', imsize=LB_imsize, cellsize=LB_cellsize, robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(LB_cont_p3+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
generate_image_png(LB_cont_p3+'.image',plot_sizes=image_png_plot_sizes['LB'],
                   color_scale_limits=[-3*rms_LB,10*rms_LB],save_folder=LB_selfcal_folder)

#J1615_ACASBLB_contp3.image
#Beam 0.181 arcsec x 0.156 arcsec (-87.30 deg)
#Flux inside disk mask: 388.77 mJy
#Peak intensity of source: 17.63 mJy/beam
#rms: 2.54e-02 mJy/beam
#Peak SNR: 694.80

LB_p4 = prefix+'_ACASBLB.p4'
os.system('rm -rf '+LB_p4)
gaincal(vis=LB_cont_p3+'.ms', caltable=LB_p4, gaintype='T', spw=LB_contspws,
        refant=LB_refant, combine='spw', calmode='p', solint='60s', minsnr=2., minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(LB_p4,xaxis='time', yaxis='GainPhase',iteraxis='spw')

""" Print calibration png file """
plotms(LB_p4,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_selfcal_folder,prefix+'_LB_gain_p4_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=LB_cont_p3+'.ms', spw=LB_contspws, spwmap = LB_spw_mapping_no_combine_scans, gaintable=[LB_p4], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
LB_cont_p4 = prefix+'_ACASBLB_contp4'
os.system('rm -rf %s.ms*' % LB_cont_p4)
split(vis=LB_cont_p3+'.ms', outputvis=LB_cont_p4+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=LB_cont_p4+'.ms', imagename = LB_cont_p4, mask=LB_mask, threshold = '0.15mJy', deconvolver='multiscale', scales=LB_scales, savemodel = 'modelcolumn', imsize=LB_imsize, cellsize=LB_cellsize, robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(LB_cont_p4+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
generate_image_png(LB_cont_p4+'.image',plot_sizes=image_png_plot_sizes['LB'],
                   color_scale_limits=[-3*rms_LB,10*rms_LB],save_folder=LB_selfcal_folder)
#J1615_ACASBLB_contp4.image
#Beam 0.181 arcsec x 0.156 arcsec (-87.30 deg)
#Flux inside disk mask: 388.65 mJy
#Peak intensity of source: 17.68 mJy/beam
#rms: 2.43e-02 mJy/beam
#Peak SNR: 728.05

LB_p5 = prefix+'_ACASBLB.p5'
os.system('rm -rf '+LB_p5)
gaincal(vis=LB_cont_p4+'.ms', caltable=LB_p5, gaintype='T', spw=LB_contspws,
        refant=LB_refant, combine='spw', calmode='p', solint='30s', minsnr=2., minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(LB_p5,xaxis='time', yaxis='GainPhase',iteraxis='spw')

""" Print calibration png file """
plotms(LB_p5,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_selfcal_folder,prefix+'_LB_gain_p5_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=LB_cont_p4+'.ms', spw=LB_contspws, spwmap = LB_spw_mapping_no_combine_scans, gaintable=[LB_p5], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
LB_cont_p5 = prefix+'_ACASBLB_contp5'
os.system('rm -rf %s.ms*' % LB_cont_p5)
split(vis=LB_cont_p4+'.ms', outputvis=LB_cont_p5+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=LB_cont_p5+'.ms', imagename = LB_cont_p5, mask=LB_mask, threshold = '0.15mJy', deconvolver='multiscale', scales=LB_scales, savemodel = 'modelcolumn', imsize=LB_imsize, cellsize=LB_cellsize, robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(LB_cont_p5+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
generate_image_png(LB_cont_p5+'.image',plot_sizes=image_png_plot_sizes['LB'],
                   color_scale_limits=[-3*rms_LB,10*rms_LB],save_folder=LB_selfcal_folder)
#J1615_ACASBLB_contp5.image
#Beam 0.181 arcsec x 0.156 arcsec (-87.30 deg)
#Flux inside disk mask: 388.68 mJy
#Peak intensity of source: 17.77 mJy/beam
#rms: 2.37e-02 mJy/beam
#Peak SNR: 750.34


self_caled_SB_visibilities = {}
self_caled_SB_visibilities = {'p5':LB_cont_p5}
all_SB_visibilities = self_caled_SB_visibilities.copy()

for self_cal_step,vis_name in all_SB_visibilities.items():
    vis_ms = vis_name+'.ms'
    nametemplate = vis_ms.replace('.ms','_EB')
    split_all_obs(msfile=vis_ms,nametemplate=nametemplate)
    for i in range(number_of_EBs['SB']+number_of_EBs['ACA']+number_of_EBs['LB']):
        EB_vis = f'{nametemplate}{i}.ms'
        export_MS(EB_vis) #export MS contents into Numpy save files

list_npz_files = []

list_npz_files = [f'{prefix}_ACASBLB_contp5_EB0.vis.npz',
                  f'{prefix}_ACASBLB_contp5_EB1.vis.npz',
                  f'{prefix}_ACASBLB_contp5_EB2.vis.npz',
                  f'{prefix}_ACASBLB_contp5_EB3.vis.npz',
                  f'{prefix}_ACASBLB_contp5_EB4.vis.npz',
                  f'{prefix}_ACASBLB_contp5_EB5.vis.npz',
                  f'{prefix}_ACASBLB_contp5_EB6.vis.npz',
                  f'{prefix}_ACASBLB_contp5_EB7.vis.npz',
                  f'{prefix}_ACASBLB_contp5_EB8.vis.npz']


plot_label = os.path.join(LB_selfcal_folder,
                          f'deprojected_vis_profiles_ACASBLB_p5.png')

plot_deprojected(filelist=list_npz_files,
                 fluxscale=[1.]*(number_of_EBs['LB']+number_of_EBs['SB']+number_of_EBs['ACA']),PA=PA,incl=incl,show_err=True,
                 plot_label=plot_label)
# Deprojected flux is much better than before self-cal

for i in np.arange(number_of_EBs['SB']+number_of_EBs['ACA']+number_of_EBs['LB']):
    estimate_flux_scale(reference=f'{prefix}_ACASBLB_contp5_EB3.vis.npz',
                            comparison=f'{prefix}_ACASBLB_contp5_EB'+str(i)+'.vis.npz',incl=incl,PA=PA,
                            plot_label=os.path.join(LB_selfcal_folder,f'{prefix}_ACASBLB_contp5_EB'+str(i)+'_to_ACASBLB_contp5_EB3_comparison.png'))
#The ratio of the fluxes of J1615_ACASBLB_contp5_EB0.vis.npz to
#J1615_ACASBLB_contp5_EB3.vis.npz is 1.07638
#The scaling factor for gencal is 1.037 for your comparison measurement
#The error on the weighted mean ratio is 1.868e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_ACASBLB_contp5_EB1.vis.npz to
#J1615_ACASBLB_contp5_EB3.vis.npz is 0.99497
#The scaling factor for gencal is 0.997 for your comparison measurement
#The error on the weighted mean ratio is 1.859e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_ACASBLB_contp5_EB2.vis.npz to
#J1615_ACASBLB_contp5_EB3.vis.npz is 0.98157
#The scaling factor for gencal is 0.991 for your comparison measurement
#The error on the weighted mean ratio is 8.692e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_ACASBLB_contp5_EB3.vis.npz to
#J1615_ACASBLB_contp5_EB3.vis.npz is 1.00000
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 1.609e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_ACASBLB_contp5_EB4.vis.npz to
#J1615_ACASBLB_contp5_EB3.vis.npz is 1.01517
#The scaling factor for gencal is 1.008 for your comparison measurement
#The error on the weighted mean ratio is 1.671e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_ACASBLB_contp5_EB5.vis.npz to
#J1615_ACASBLB_contp5_EB3.vis.npz is 0.91846
#The scaling factor for gencal is 0.958 for your comparison measurement
#The error on the weighted mean ratio is 4.291e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_ACASBLB_contp5_EB6.vis.npz to
#J1615_ACASBLB_contp5_EB3.vis.npz is 1.01127
#The scaling factor for gencal is 1.006 for your comparison measurement
#The error on the weighted mean ratio is 3.871e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_ACASBLB_contp5_EB7.vis.npz to
#J1615_ACASBLB_contp5_EB3.vis.npz is 0.97393
#The scaling factor for gencal is 0.987 for your comparison measurement
#The error on the weighted mean ratio is 2.670e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1615_ACASBLB_contp5_EB8.vis.npz to
#J1615_ACASBLB_contp5_EB3.vis.npz is 0.95829
#The scaling factor for gencal is 0.979 for your comparison measurement
#The error on the weighted mean ratio is 3.295e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

# ACA EB0 is still of by ~10%. LB EBs have MUCH improved de-coherence, still not
# perfect beyond 300 klambda, as seen for other sources.

# Let's see how amplitude self-cal improves things






""" Clean down to 1 sigma for amplitude self-cal"""
tclean_wrapper(vis=LB_cont_p5+'.ms', imagename = LB_cont_p5, mask=LB_mask, threshold = '0.024mJy', deconvolver='multiscale', scales=LB_scales, savemodel = 'modelcolumn', imsize=LB_imsize, cellsize=LB_cellsize, robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(LB_cont_p5+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
#J1615_ACASBLB_contp5.image
#Beam 0.181 arcsec x 0.156 arcsec (-87.30 deg)
#Flux inside disk mask: 388.49 mJy
#Peak intensity of source: 17.72 mJy/beam
#rms: 2.22e-02 mJy/beam
#Peak SNR: 797.08

""" Amplitude self-cal"""
LB_ap0 = prefix+'_ACASBLB.ap0'
os.system('rm -rf '+LB_ap0)
gaincal(vis=LB_cont_p5+'.ms', caltable=LB_ap0, gaintype='T', spw=LB_contspws,
        refant=LB_refant, combine='spw, scan', calmode='ap', solint='inf', minsnr=5.0,
        minblperant=4, solnorm=False)
#No flagging

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(LB_ap0,xaxis='time', yaxis='GainPhase',iteraxis='spw')
plotms(LB_ap0,xaxis='time', yaxis='GainAmp',iteraxis='spw')

""" Print calibration png file """
plotms(LB_ap0,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_selfcal_folder,prefix+'_LB_gain_ap0_phase_vs_time.png'))
plotms(LB_ap0,xaxis='time', yaxis='GainAmp',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_selfcal_folder,prefix+'_LB_gain_ap0_amp_vs_time.png'))

""" Apply the solutions """
applycal(vis=LB_cont_p5+'.ms', spw=LB_contspws, spwmap = LB_spw_mapping_combine_scans,
         gaintable=[LB_ap0], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
LB_cont_ap0 = prefix+'_ACASBLB_contap0'
os.system('rm -rf %s.ms*' % LB_cont_ap0)
split(vis=LB_cont_p5+'.ms', outputvis=LB_cont_ap0+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
#again clean down to 1 sigma
tclean_wrapper(vis=LB_cont_ap0+'.ms', imagename = LB_cont_ap0, mask=LB_mask,
               threshold = '0.024mJy', deconvolver='multiscale', scales=LB_scales,
               savemodel = 'modelcolumn', imsize=LB_imsize, cellsize=LB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(LB_cont_ap0+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
generate_image_png(LB_cont_ap0+'.image',plot_sizes=image_png_plot_sizes['LB'],
                   color_scale_limits=[-3*rms_LB,10*rms_LB],save_folder=LB_selfcal_folder)
#J1615_ACASBLB_contap0.image
#Beam 0.182 arcsec x 0.157 arcsec (-85.32 deg)
#Flux inside disk mask: 387.53 mJy
#Peak intensity of source: 17.96 mJy/beam
#rms: 2.10e-02 mJy/beam
#Peak SNR: 857.00




self_caled_SB_visibilities = {}
self_caled_SB_visibilities = {'ap0':LB_cont_ap0}
all_SB_visibilities = self_caled_SB_visibilities.copy()

for self_cal_step,vis_name in all_SB_visibilities.items():
    #split out SB EBs
    vis_ms = vis_name+'.ms'
    nametemplate = vis_ms.replace('.ms','_EB')
    split_all_obs(msfile=vis_ms,nametemplate=nametemplate)
    #we only compare SB to LB, not ACA to LB
    for i in range(number_of_EBs['SB']+number_of_EBs['ACA']+number_of_EBs['LB']):
        EB_vis = f'{nametemplate}{i}.ms'
        export_MS(EB_vis) #export MS contents into Numpy save files


list_npz_files = []

list_npz_files = [f'{prefix}_ACASBLB_contap0_EB0.vis.npz',
                  f'{prefix}_ACASBLB_contap0_EB1.vis.npz',
                  f'{prefix}_ACASBLB_contap0_EB2.vis.npz',
                  f'{prefix}_ACASBLB_contap0_EB3.vis.npz',
                  f'{prefix}_ACASBLB_contap0_EB4.vis.npz',
                  f'{prefix}_ACASBLB_contap0_EB5.vis.npz',
                  f'{prefix}_ACASBLB_contap0_EB6.vis.npz',
                  f'{prefix}_ACASBLB_contap0_EB7.vis.npz',
                  f'{prefix}_ACASBLB_contap0_EB8.vis.npz']


plot_label = os.path.join(LB_selfcal_folder,
                          f'deprojected_vis_profiles_ACASBLB_ap0.png')

plot_deprojected(filelist=list_npz_files,
                 fluxscale=[1.]*(number_of_EBs['LB']+number_of_EBs['SB']+number_of_EBs['ACA']),PA=PA,incl=incl,show_err=True,
                 plot_label=plot_label)
# Deprojected flux is much better than before self-cal

for i in np.arange(number_of_EBs['SB']+number_of_EBs['ACA']+number_of_EBs['LB']):
    estimate_flux_scale(reference=f'{prefix}_ACASBLB_contap0_EB3.vis.npz',
                            comparison=f'{prefix}_ACASBLB_contap0_EB'+str(i)+'.vis.npz',incl=incl,PA=PA,
                            plot_label=os.path.join(LB_selfcal_folder,f'{prefix}_ACASBLB_contap0_EB'+str(i)+'_to_ACASBLB_contap0_EB3_comparison.png'))

#The ratio of the fluxes of LkCa_15_ACASBLB_contap1_EB0.vis.npz to
#LkCa_15_ACASBLB_contap1_EB4.vis.npz is 1.00785
#The scaling factor for gencal is 1.004 for your comparison measurement
#The error on the weighted mean ratio is 1.326e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of LkCa_15_ACASBLB_contap1_EB1.vis.npz to
#LkCa_15_ACASBLB_contap1_EB4.vis.npz is 1.01119
#The scaling factor for gencal is 1.006 for your comparison measurement
#The error on the weighted mean ratio is 1.900e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of LkCa_15_ACASBLB_contap1_EB2.vis.npz to
#LkCa_15_ACASBLB_contap1_EB4.vis.npz is 1.00489
#The scaling factor for gencal is 1.002 for your comparison measurement
#The error on the weighted mean ratio is 1.981e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of LkCa_15_ACASBLB_contap1_EB3.vis.npz to
#LkCa_15_ACASBLB_contap1_EB4.vis.npz is 1.00252
#The scaling factor for gencal is 1.001 for your comparison measurement
#The error on the weighted mean ratio is 3.392e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of LkCa_15_ACASBLB_contap1_EB4.vis.npz to
#LkCa_15_ACASBLB_contap1_EB4.vis.npz is 1.00000
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 3.090e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of LkCa_15_ACASBLB_contap1_EB5.vis.npz to
#LkCa_15_ACASBLB_contap1_EB4.vis.npz is 0.99452
#The scaling factor for gencal is 0.997 for your comparison measurement
#The error on the weighted mean ratio is 4.934e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of LkCa_15_ACASBLB_contap1_EB6.vis.npz to
#LkCa_15_ACASBLB_contap1_EB4.vis.npz is 1.00557
#The scaling factor for gencal is 1.003 for your comparison measurement
#The error on the weighted mean ratio is 4.993e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of LkCa_15_ACASBLB_contap1_EB7.vis.npz to
#LkCa_15_ACASBLB_contap1_EB4.vis.npz is 1.00025
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 4.752e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of LkCa_15_ACASBLB_contap1_EB8.vis.npz to
#LkCa_15_ACASBLB_contap1_EB4.vis.npz is 1.00195
#The scaling factor for gencal is 1.001 for your comparison measurement
#The error on the weighted mean ratio is 3.589e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

# Things are MUCH better after one round of ap cal.
# Let's try a second round, where we will have to separate things by scan

LB_ap1 = prefix+'_ACASBLB.ap1'
os.system('rm -rf '+LB_ap1)
gaincal(vis=LB_cont_ap0+'.ms', caltable=LB_ap1, gaintype='T', spw=LB_contspws,
        refant=LB_refant, combine='spw', calmode='ap', solint='inf', minsnr=5.0,
        minblperant=4, solnorm=False)
#No flagging

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(LB_ap1,xaxis='time', yaxis='GainPhase',iteraxis='spw')
plotms(LB_ap1,xaxis='time', yaxis='GainAmp',iteraxis='spw')
#very minor manual flagging

""" Print calibration png file """
plotms(LB_ap1,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_selfcal_folder,prefix+'_LB_gain_ap1_phase_vs_time.png'))
plotms(LB_ap1,xaxis='time', yaxis='GainAmp',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_selfcal_folder,prefix+'_LB_gain_ap1_amp_vs_time.png'))

""" Apply the solutions """
applycal(vis=LB_cont_ap0+'.ms', spw=LB_contspws, spwmap = LB_spw_mapping_no_combine_scans,
         gaintable=[LB_ap1], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
LB_cont_ap1 = prefix+'_ACASBLB_contap1'
os.system('rm -rf %s.ms*' % LB_cont_ap1)
split(vis=LB_cont_ap0+'.ms', outputvis=LB_cont_ap1+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
#again clean down to 1 sigma
tclean_wrapper(vis=LB_cont_ap1+'.ms', imagename = LB_cont_ap1, mask=LB_mask,
               threshold = '0.024mJy', deconvolver='multiscale', scales=LB_scales,
               savemodel = 'modelcolumn', imsize=LB_imsize, cellsize=LB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(LB_cont_ap1+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
generate_image_png(LB_cont_ap1+'.image',plot_sizes=image_png_plot_sizes['LB'],
                   color_scale_limits=[-3*rms_LB,10*rms_LB],save_folder=LB_selfcal_folder)
#J1615_ACASBLB_contap1.image
#Beam 0.182 arcsec x 0.157 arcsec (-85.43 deg)
#Flux inside disk mask: 387.10 mJy
#Peak intensity of source: 17.96 mJy/beam
#rms: 2.04e-02 mJy/beam
#Peak SNR: 878.53

self_caled_SB_visibilities = {}
self_caled_SB_visibilities = {'ap1':LB_cont_ap1}
all_SB_visibilities = self_caled_SB_visibilities.copy()

for self_cal_step,vis_name in all_SB_visibilities.items():
    #split out SB EBs
    vis_ms = vis_name+'.ms'
    nametemplate = vis_ms.replace('.ms','_EB')
    split_all_obs(msfile=vis_ms,nametemplate=nametemplate)
    #we only compare SB to LB, not ACA to LB
    for i in range(number_of_EBs['SB']+number_of_EBs['ACA']+number_of_EBs['LB']):
        EB_vis = f'{nametemplate}{i}.ms'
        export_MS(EB_vis) #export MS contents into Numpy save files


list_npz_files = []

list_npz_files = [f'{prefix}_ACASBLB_contap1_EB0.vis.npz',
                  f'{prefix}_ACASBLB_contap1_EB1.vis.npz',
                  f'{prefix}_ACASBLB_contap1_EB2.vis.npz',
                  f'{prefix}_ACASBLB_contap1_EB3.vis.npz',
                  f'{prefix}_ACASBLB_contap1_EB4.vis.npz',
                  f'{prefix}_ACASBLB_contap1_EB5.vis.npz',
                  f'{prefix}_ACASBLB_contap1_EB6.vis.npz',
                  f'{prefix}_ACASBLB_contap1_EB7.vis.npz',
                  f'{prefix}_ACASBLB_contap1_EB8.vis.npz']


plot_label = os.path.join(LB_selfcal_folder,
                          f'deprojected_vis_profiles_ACASBLB_ap1.png')

plot_deprojected(filelist=list_npz_files,
                 fluxscale=[1.]*(number_of_EBs['LB']+number_of_EBs['SB']+number_of_EBs['ACA']),PA=PA,incl=incl,show_err=True,
                 plot_label=plot_label)
# Deprojected flux is much better than before self-cal

for i in np.arange(number_of_EBs['SB']+number_of_EBs['ACA']+number_of_EBs['LB']):
    estimate_flux_scale(reference=f'{prefix}_ACASBLB_contap1_EB3.vis.npz',
                            comparison=f'{prefix}_ACASBLB_contap1_EB'+str(i)+'.vis.npz',incl=incl,PA=PA,
                            plot_label=os.path.join(LB_selfcal_folder,f'{prefix}_ACASBLB_contap1_EB'+str(i)+'_to_ACASBLB_contap1_EB3_comparison.png'))



""" Split out final continuum ms table, with a 30s timebin
"""
LB_cont_averaged = prefix+'_time_ave_continuum'
os.system(f'rm -rf {LB_cont_averaged}.ms*')
split(vis=LB_cont_ap1+'.ms', outputvis=LB_cont_averaged+'.ms', datacolumn='data',
      keepflags=False, timebin='30s')


"""
Now apply these solutions to the line data
"""
calibrate_linedata_folder = get_figures_folderpath('10_apply_cal_to_lines')
make_figures_folder(calibrate_linedata_folder)

""" Check that lines are not flagged in not averaged data"""
for params in data_params.values():
    plotms(vis=params['vis'],
            xaxis='channel',
            yaxis='amplitude',
            field=params['field'],
            ydatacolumn='data',
            avgtime='1e8',
            avgscan=True,
            avgbaseline=True,
            coloraxis='corr',
            iteraxis='spw',
            showgui = False,
            exprange='all',
            plotfile=os.path.join(calibrate_linedata_folder,
                                  prefix+'_'+params['name']+'_chan-v-amp_preselfcal_after_flagging.png')
            )


""" Apply gaintables of individual EBs"""
for params in data_params_ACA.values():
    single_EB_p1 = prefix+'_'+params['name']+'_initcont.p1'
    applycal(vis=prefix+'_'+params['name']+'.ms', spw='0~3',spwmap=[0,0,0,0],
             gaintable=[single_EB_p1], interp='linearPD', applymode='calonly', calwt=True)
    os.system('rm -rf '+prefix+'_'+params['name']+'_no_ave_selfcal.ms')
    split(vis=prefix+'_'+params['name']+'.ms',
          outputvis=prefix+'_'+params['name']+'_no_ave_selfcal.ms',
          datacolumn='corrected')

for params in data_params_SB.values():
    single_EB_p1 = prefix+'_'+params['name']+'_initcont.p1'
    applycal(vis=prefix+'_'+params['name']+'.ms', spw='0~3',spwmap=[0,0,0,0],
             gaintable=[single_EB_p1], interp='linearPD', applymode='calonly', calwt=True)
    os.system('rm -rf '+prefix+'_'+params['name']+'_no_ave_selfcal.ms')
    split(vis=prefix+'_'+params['name']+'.ms',
          outputvis=prefix+'_'+params['name']+'_no_ave_selfcal.ms',
          datacolumn='corrected')



# LB EB0 has 80 spws
single_EB0_spw_mapping_LB = np.zeros(80)
single_EB0_contspws_LB = '0~79'

applycal(vis=prefix+'_'+'LB_EB0.ms', spw=single_EB0_contspws_LB,spwmap=single_EB0_spw_mapping_LB,
    gaintable=[single_EB0_p1], interp='linearPD', applymode='calonly', calwt=True)
os.system('rm -rf '+prefix+'_'+'LB_EB0'+'_no_ave_selfcal.ms')
split(vis=prefix+'_'+'LB_EB0.ms',
      outputvis=prefix+'_'+'LB_EB0'+'_no_ave_selfcal.ms',
      datacolumn='corrected')

# LB EB1 has 72 spws
single_EB1_spw_mapping_LB = np.zeros(72)
single_EB1_contspws_LB = '0~71'

applycal(vis=prefix+'_'+'LB_EB1.ms', spw=single_EB1_contspws_LB,spwmap=single_EB1_spw_mapping_LB,
    gaintable=[single_EB1_p1], interp='linearPD', applymode='calonly', calwt=True)
os.system('rm -rf '+prefix+'_'+'LB_EB1'+'_no_ave_selfcal.ms')
split(vis=prefix+'_'+'LB_EB1.ms',
      outputvis=prefix+'_'+'LB_EB1'+'_no_ave_selfcal.ms',
      datacolumn='corrected')

# LB EB2 has 4 spw
single_EB2_spw_mapping_LB = np.zeros(4)
single_EB2_contspws_LB = '0~3'

applycal(vis=prefix+'_'+'LB_EB2.ms', spw=single_EB2_contspws_LB,spwmap=single_EB2_spw_mapping_LB,
    gaintable=[single_EB2_p1], interp='linearPD', applymode='calonly', calwt=True)
os.system('rm -rf '+prefix+'_'+'LB_EB2'+'_no_ave_selfcal.ms')
split(vis=prefix+'_'+'LB_EB2.ms',
      outputvis=prefix+'_'+'LB_EB2'+'_no_ave_selfcal.ms',
      datacolumn='corrected')

# special case for LB data since we have 4 spws in EB3.
single_EB3_spw_mapping_LB = np.zeros(4)
single_EB3_contspws_LB = '0~3'

applycal(vis=prefix+'_'+'LB_EB3.ms', spw=single_EB3_contspws_LB,spwmap=single_EB3_spw_mapping_LB,
    gaintable=[single_EB3_p1], interp='linearPD', applymode='calonly', calwt=True)
os.system('rm -rf '+prefix+'_'+'LB_EB3'+'_no_ave_selfcal.ms')
split(vis=prefix+'_'+'LB_EB3.ms',
      outputvis=prefix+'_'+'LB_EB3'+'_no_ave_selfcal.ms',
      datacolumn='corrected')

###
# ALIGN DATA: we re-align the no_ave data, as we have done for the "initcont" ms tables.
# We go from *_no_ave_selfcal.ms to *_no_ave_shift.ms

reference_ms = {'LB':reference_for_LB_alignment,
                'SB':reference_for_SB_alignment,
                'ACA':reference_for_ACA_alignment}
for params in data_params.values():
    unshifted_ms = f'{prefix}_{params["name"]}_no_ave_selfcal.ms'
    os.system('rm -rf '+prefix+'_'+params['name']+'_no_ave_selfcal_shift.ms')
    os.system('rm -rf '+prefix+'_'+params['name']+'_no_ave_shift.ms')

    array_key,_ = params['name'].split('_') #LB, SB or ACA
    offset = alignment_offsets[params['name']]
    #npix and cell_size are not needed because we do not fit any offset
    alignment.align_measurement_sets(
            reference_ms=reference_ms[array_key],align_ms=[unshifted_ms],
            align_offsets=[offset],npix=None,cell_size=None)

###


"""
We do not rescale fluxes for J1615
"""


""" Concat not averaged ACA data """
ACA_combined = prefix+'_ACA_no_ave_concat'
os.system('rm -rf %s.ms*' % ACA_combined)
concat(vis=[f'{prefix}_ACA_EB{i}_no_ave_selfcal_shift.ms' for i in range(number_of_EBs['ACA'])],
       concatvis=ACA_combined+'.ms', dirtol='0.1arcsec', copypointing=False)

listobs(vis=ACA_combined+'.ms',listfile=ACA_combined+'.ms.txt',overwrite=True)

applycal(vis=ACA_combined+'.ms', spw=ACA_contspws,
         gaintable=[prefix+'_ACA.p1',prefix+'_ACA.p2'],
         spwmap = [[0,1,2,3,4,5,6,7,8,9,10,11],ACA_spw_mapping],interp=['linear','linearPD'], calwt=True,
         applymode='calonly',flagbackup=False)

os.system('rm -rf '+prefix+'_ACA_no_ave_selfcal.ms*')
split(vis=ACA_combined+'.ms', outputvis=prefix+'_ACA_no_ave_selfcal.ms',
      datacolumn='corrected')

""" Concat not averaged SB data """
SB_combined = prefix+'_ACASB_no_ave_concat'
os.system('rm -rf %s.ms*' % SB_combined)

concat(vis=[f'{prefix}_ACA_no_ave_selfcal.ms']+[f'{prefix}_SB_EB{i}_no_ave_selfcal_shift.ms'
                                                for i in range(number_of_EBs['SB'])],
       concatvis=SB_combined+'.ms', dirtol='0.1arcsec', copypointing=False)

listobs(vis=SB_combined+'.ms',listfile=SB_combined+'.ms.txt',overwrite=True)

#Be careful here to be sure to apply the right gain tables, in particular,
#if you did the SB self-cal twice (e.g. SB selfcal #1 on flux-unscaled MS, SB selfcal
# #2 on scaled MS)
applycal(vis=SB_combined+'.ms', spw=SB_contspws,
         gaintable=[prefix+'_ACASB.p1',prefix+'_ACASB.p2',
                    prefix+'_ACASB.p3',prefix+'_ACASB.p4',
                    prefix+'_ACASB.p5',prefix+'_ACASB.p6'],
         spwmap = [SB_spw_mapping]*6,interp=['linearPD']*6, calwt=True,
         applymode='calonly',flagbackup=False)

os.system('rm -rf '+prefix+'_ACASB_no_ave_selfcal.ms*')
split(vis=SB_combined+'.ms', outputvis=prefix+'_ACASB_no_ave_selfcal.ms',
      datacolumn='corrected')

""" Concat not averaged LB data """

LB_combined = prefix+'_ACASBLB_no_ave_concat'
os.system('rm -rf %s.ms*' % LB_combined)

concat(vis=[f'{prefix}_ACASB_no_ave_selfcal.ms']+[f'{prefix}_LB_EB{i}_no_ave_selfcal_shift.ms'
                                                  for i in range(number_of_EBs['LB'])],
       concatvis=LB_combined+'.ms', dirtol='0.1arcsec', copypointing=False)

listobs(vis=LB_combined+'.ms',listfile=LB_combined+'.ms.txt',overwrite=True)

applycal(vis=LB_combined+'.ms', spw=LB_contspws,
         gaintable=[prefix+'_ACASBLB.p1',prefix+'_ACASBLB.p2',prefix+'_ACASBLB.p3',
                    prefix+'_ACASBLB.p4',prefix+'_ACASBLB.p5',prefix+'_ACASBLB.ap0',
                    prefix+'_ACASBLB.ap1'],
         spwmap = [LB_spw_mapping_combine_scans,LB_spw_mapping_no_combine_scans,
                    LB_spw_mapping_no_combine_scans,LB_spw_mapping_no_combine_scans,
                    LB_spw_mapping_no_combine_scans,LB_spw_mapping_combine_scans,
                    LB_spw_mapping_no_combine_scans],interp=['linearPD']*7,
         calwt=True, applymode='calonly',flagbackup=False)

ACASBLB_no_ave_final = f'{prefix}_ACASBLB_no_ave_selfcal_time_ave.ms'
os.system(f'rm -rf {ACASBLB_no_ave_final}*')
""" time average of 30s, tests show there is no different with data without time average """
split(vis=LB_combined+'.ms', outputvis=ACASBLB_no_ave_final,
      datacolumn='corrected', timebin = '30s', keepflags=False)

#use the output of get_flagchannels at the beginning of the script to define fitspw. We had


# Flagchannels input string for ACA_EB0: '0:959~3127, 2:921~3170, 3:910~3178'
# Flagchannels input string for ACA_EB1: '0:961~3129, 2:918~3167, 3:915~3183'
# Flagchannels input string for ACA_EB2: '0:962~3130, 2:919~3168, 3:917~3185'
# Flagchannels input string for SB_EB0: '0:837~3005, 2:792~3041, 3:789~3057'
# Flagchannels input string for SB_EB1: '0:837~3005, 2:792~3041, 3:789~3057'

# Flagchannels input string for LB_EB0: '0:832~3000, 2:799~3047, 3:784~3051, 4:832~3000, 6:799~3047, 7:784~3051, 8:832~3000, 10:799~3047, 11:784~3051, 12:832~3000, 14:798~3047, 15:783~3051, 16:831~2999, 18:799~3048, 19:784~3052, 20:831~2999, 22:799~3047, 23:784~3052, 24:832~3000, 26:799~3047, 27:784~3051, 28:832~3000, 30:798~3046, 31:783~3051, 32:832~3000, 34:799~3047, 35:784~3051, 36:832~3000, 38:798~3046, 39:783~3051, 40:831~2999, 42:800~3048, 43:785~3052, 44:832~3000, 46:799~3047, 47:784~3051, 48:833~3001, 50:798~3046, 51:783~3050, 52:832~3000, 54:798~3046, 55:783~3051, 56:833~3001, 58:797~3046, 59:782~3050, 60:832~3000, 62:798~3047, 63:783~3051, 64:832~3000, 66:798~3047, 67:784~3051, 68:832~3000, 70:798~3047, 71:783~3051, 72:831~2999, 74:799~3048, 75:785~3052, 76:831~2999, 78:799~3048, 79:784~3052'
# Flagchannels input string for LB_EB1: '0:832~3000, 2:799~3047, 3:784~3051, 4:832~3000, 6:798~3047, 7:783~3051, 8:833~3001, 10:797~3046, 11:782~3050, 12:833~3001, 14:798~3046, 15:783~3050, 16:832~3000, 18:799~3047, 19:784~3051, 20:831~2999, 22:799~3048, 23:784~3052, 24:832~2999, 26:799~3047, 27:784~3052, 28:831~2999, 30:799~3047, 31:784~3052, 32:831~2999, 34:799~3048, 35:784~3052, 36:831~2999, 38:799~3047, 39:784~3052, 40:831~2999, 42:799~3048, 43:784~3052, 44:832~3000, 46:799~3047, 47:784~3051, 48:831~2999, 50:799~3048, 51:784~3052, 52:831~2998, 54:800~3048, 55:785~3053, 56:831~2999, 58:799~3048, 59:784~3052, 60:830~2998, 62:800~3049, 63:785~3053, 64:833~3000, 66:798~3046, 67:783~3050, 68:832~3000, 70:798~3047, 71:783~3051'
# Flagchannels input string for LB_EB2: '0:833~3001, 2:797~3046, 3:781~3049'
# Flagchannels input string for LB_EB3: '0:833~3001, 2:797~3046, 3:781~3049'




fitspw =  '0:959~3127, 1:0, 2:921~3170, 3:910~3178,'\
         +'4:961~3129, 5:0, 6:918~3167, 7:915~3183,'\
         +'8:962~3130, 9:0, 10:919~3168, 11:917~3185,'\
         +'12:837~3005, 13:0, 14:792~3041, 15:789~3057,'\
         +'16:837~3005, 17:0, 18:792~3041, 19:789~3057,'\
         +'20:832~3000, 21:0, 22:799~3047, 23:784~3051, 24:832~3000, 25:0, 26:799~3047, 27:784~3051, 28:832~3000, 29:0, 30:799~3047, 31:784~3051, 32:832~3000, 33:0, 34:798~3047, 35:783~3051, 36:831~2999, 37:0, 38:799~3048, 39:784~3052, 40:831~2999, 41:0, 42:799~3047, 43:784~3052, 44:832~3000, 45:0, 46:799~3047, 47:784~3051, 48:832~3000, 49:0, 50:798~3046, 51:783~3051, 52:832~3000, 53:0, 54:799~3047, 55:784~3051, 56:832~3000, 57:0, 58:798~3046, 59:783~3051, 60:831~2999, 61:0, 62:800~3048, 63:785~3052, 64:832~3000, 65:0, 66:799~3047, 67:784~3051, 68:833~3001, 69:0, 70:798~3046, 71:783~3050, 72:832~3000, 73:0, 74:798~3046, 75:783~3051, 76:833~3001, 77:0, 78:797~3046, 79:782~3050, 80:832~3000, 81:0, 82:798~3047, 83:783~3051, 84:832~3000, 85:0, 86:798~3047, 87:784~3051, 88:832~3000, 89:0, 90:798~3047, 91:783~3051, 92:831~2999, 93:0, 94:799~3048, 95:785~3052, 96:831~2999, 97:0, 98:799~3048, 99:784~3052,'\
         +'100:832~3000, 101:0, 102:799~3047, 103:784~3051, 104:832~3000, 105:0, 106:798~3047, 107:783~3051, 108:833~3001, 109:0, 110:797~3046, 111:782~3050, 112:833~3001, 113:0, 114:798~3046, 115:783~3050, 116:832~3000, 117:0, 118:799~3047, 119:784~3051, 120:831~2999, 121:0, 122:799~3048, 123:784~3052, 124:832~2999, 125:0, 126:799~3047, 127:784~3052, 128:831~2999, 129:0, 130:799~3047, 131:784~3052, 132:831~2999, 133:0, 134:799~3048, 135:784~3052, 136:831~2999, 137:0, 138:799~3047, 139:784~3052, 140:831~2999, 141:0, 142:799~3048, 143:784~3052, 144:832~3000, 145:0, 146:799~3047, 147:784~3051, 148:831~2999, 149:0, 150:799~3048, 151:784~3052, 152:831~2998, 153:0, 154:800~3048, 155:785~3053, 156:831~2999, 157:0, 158:799~3048, 159:784~3052, 160:830~2998, 161:0, 162:800~3049, 163:785~3053, 164:833~3000, 165:0, 166:798~3046, 167:783~3050, 168:832~3000, 169:0, 170:798~3047, 171:783~3051,'\
         +'172:833~3001, 173:0, 174:797~3046, 175:781~3049,'\
         +'176:833~3001, 177:0, 178:797~3046, 179:781~3049'





contsub_vis = f'{ACASBLB_no_ave_final}.contsub'
os.system(f'rm -rf {contsub_vis}*')
uvcontsub(vis=ACASBLB_no_ave_final, spw='0~179', fitspw=fitspw,
          excludechans=True, solint='int', fitorder=1, want_cont=False)

# Split final ms table into separate spws for 12CO, 13CO, CS and continuum

#12CO
vis_12CO = ACASBLB_no_ave_final[:-3]+'_12CO.ms'
os.system(f'rm -rf {vis_12CO}*')
spw_12CO = '3,7,11,15,19,23,27,31,35,39,43,47,51,55,59,63,67,71,75,79,83,87,91,95,99,103,107,111,115,119,123,127,131,135,139,143,147,151,155,159,163,167,171,175,179'
split(vis=ACASBLB_no_ave_final,outputvis=vis_12CO,spw=spw_12CO,
      datacolumn='data', keepflags=False)
split(vis=contsub_vis,outputvis=f'{vis_12CO}.contsub',spw=spw_12CO,
      datacolumn='data', keepflags=False)

#13CO
vis_13CO = ACASBLB_no_ave_final[:-3]+'_13CO.ms'
os.system(f'rm -rf {vis_13CO}*')
spw_13CO = '0,4,8,12,16,20,24,28,32,36,40,44,48,52,56,60,64,68,72,76,80,84,88,92,96,100,104,108,112,116,120,124,128,132,136,140,144,148,152,156,160,164,168,172,176'
split(vis=ACASBLB_no_ave_final,outputvis=vis_13CO,spw=spw_13CO,
      datacolumn='data', keepflags=False)
split(vis=contsub_vis,outputvis=f'{vis_13CO}.contsub',spw=spw_13CO,
      datacolumn='data', keepflags=False)

#CS
vis_CS = ACASBLB_no_ave_final[:-3]+'_CS.ms'
os.system(f'rm -rf {vis_CS}*')
spw_CS = '2,6,10,14,18,22,26,30,34,38,42,46,50,54,58,62,66,70,74,78,82,86,90,94,98,102,106,110,114,118,122,126,130,134,138,142,146,150,154,158,162,166,170,174,178'
split(vis=ACASBLB_no_ave_final,outputvis=vis_CS,spw=spw_CS,
      datacolumn='data', keepflags=False)
split(vis=contsub_vis,outputvis=f'{vis_CS}.contsub',spw=spw_CS,
      datacolumn='data', keepflags=False)

#continuum spw
vis_continuum = ACASBLB_no_ave_final[:-3]+'_contspw.ms'
os.system(f'rm -rf {vis_continuum}*')
spw_continuum = '1,5,9,13,17,21,25,29,33,37,41,45,49,53,57,61,65,69,73,77,81,85,89,93,97,101,105,109,113,117,121,125,129,133,137,141,145,149,153,157,161,165,169,173,177'
split(vis=ACASBLB_no_ave_final,outputvis=vis_continuum,spw=spw_continuum,
      datacolumn='data', keepflags=False)
split(vis=contsub_vis,outputvis=f'{vis_continuum}.contsub',spw=spw_continuum,
      datacolumn='data', keepflags=False)
split(vis=contsub_vis,outputvis=f'{vis_continuum}.contsub',spw=spw_continuum,
      datacolumn='data', keepflags=False)
